Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SML : why functions always take one-argument make language flexible

Tags:

function

sml

I have learned (from a SML book) that functions in SML always takes just one argument: a tuple. A function that takes multiple arguments is just a function that takes one tuple as argument, implemented with a tuple binding in function binding. I understand this point.

But after this, the book says something that I don't understand:

this point makes SML language flexible and elegant design, and you can do something useful that you cannot do in Java.

Why does this design make the language Flexible? What is the text referring to, that SML can but java cannot?

like image 926
hqt Avatar asked Jan 15 '23 09:01

hqt


1 Answers

Using tuples instead of multiple arguments adds flexibility in the sense that higher-order functions can work with functions of any "arity". For example to create the list [f x, f y, f z], you can use the higher-order function map like this:

map f [x, y, z]

That's easy enough - you can do that in any language. But now let's consider the case where f actually needs two arguments. If f were a true binary function (supposing SML had such functions), we'd need a different version of map that can work with binary functions instead of unary functions (and if we'd want to use a 3-ary functions, we'd need a version for those as well). However using tuples we can just write it like this:

map f [(x,a), (y,b), (z,c)]

This will create the list [f (x,a), f (y,b), f (z,c)].

PS: It's not really true that all functions that need multiple arguments take tuples in SML. Often functions use currying, not tuples, to represent multiple arguments, but I suppose your book hasn't gotten to currying yet. Curried functions can't be used in the same way as described above, so they're not as general in that sense.

like image 188
sepp2k Avatar answered Jan 31 '23 11:01

sepp2k