ID:1087481
 
This is kind of a silly thing, but I like comparing languages and how to write basic functions within them. I've used DM for years and I'm just learning JavaScript; here's how I would write an add() and sum() function in both:

// DM
proc
add(a, b)
return a + b

sum()
. = 0

for(var/i = 1 to args.len)
. = add(., args[i])


// JavaScript
function add(a, b) {
"use strict";

return a + b;
}

function sum() {
"use strict";

var i,
total = 0;

for (i = 0; i < arguments.length; i += 1) {
total = add(total, arguments[i]);
}

return total;
}


I'd love to see others write these two functions in other languages. :)
Sorry but I keep getting NaN with the JavaScript snippet you supplied, might just be me?

document.write("Results : " + sum(400, 600))

or with
document.write("Results : " + sum(400))


http://jsfiddle.net/X8h8H/
In response to A.T.H.K
Doh, when I rewrote it from memory I forgot to set total to 0. Thanks for pointing that out!
That's ok, strange that it keeps on printing out the exact same value of sum(400) though hah.
C++


#include "stdafx.h"
#include <iostream>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}


int Add(int a, int b)
{
return a + b;
}

void main()
{
int x;
int y;

cout<<"Input your first interger to add:";
cin>>x;
cin.ignore();
cout<<"Input your second interget to add:";
cin>>y;
cin.ignore();
cout<<"The sum of your numbers is:"<< Add(x,y) <<"\n";
cin.ignore();
}


PHP

function add($a,$b){
$result = $a + $b;
return 'Calculated sum is - '.$result;
}
echo add(2,4);


I didn't see the need to have a separate functions to calculate the two inputs..
Dart (Google)
add(a, b) => a + b
In response to A.T.H.K
A.T.H.K wrote:
PHP

> function add($a, $b){return 'Calculated sum is - '.$a + $b;}
> echo add(2,4);
>

I didn't see the need to have a separate functions to calculate the two inputs..


The other function (sum) allowed you to enter any number of sums, as it looped through the function's argument list.
//Python

def Add(a,b):
return a + b

if __name__=="__main__":
x = input("A: ")
y = input("B: ")
Add(x,y)