Is the o
composition operator (eg. val x = foo o bar
, where foo
and bar
are both functions), only usable on single-argument functions and/or functions with equal numbers of arguments? If not, what is the syntax for, say, composing foo(x,y)
with bar(x)
.
Every function in SML takes exactly one value and returns exactly one result. For instance, our square_root function takes one real value and returns one real value. The advantage of always taking one argument and returning one result is that the language is extremely uniform.
The form ''a is a so-called equality type variable, which means that it can only be substituted by types that admit the use of the equality operator = (or <> ) on their values. For example, this function: fun contains(x, []) = false | contains(x, y::ys) = x = y orelse contains (x, ys)
If you type the square_root declaration above into the SML top-level, it responds with: val square_root : fn real -> real. indicating that you've declared a variable (square_root), that its value is a function (fn), and that its type is a function from reals to reals.
As Michael already said, yes, SML only has single argument functions. I want to elaborate a bit, though.
The following function:
fun foo (x,y) = x + y
Has the type:
fn : int * int -> int
Which means that the first argument is a tuple of two ints. So you could do something like:
(sign o foo) (4,~5)
Which would give you the same as sign (foo (4,~5))
.
Okay, but what about something like this?
fun bar x y = x + y
It has the type:
fn : int -> int -> int
Which means that bar actually takes just one integer, and returns a function. So you can't do this:
(sign o bar) 4 ~5
Because bar returns a function, and sign takes an integer. You can do this, though:
(sign o bar 4) ~5
Because bar 4
is a function that adds 4 to a number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With