Basilm
Basilm

Reputation: 23

How to declare an argument as a function in SML?

my question goes like this: how can I define a function , that receives a function without using type constraints or in other words, without having to type fun f1(f2:type->type) ? I'm trying to think of a way that uses the argument f2 as a function but its not getting anywhere. Any ideas?

Upvotes: 0

Views: 373

Answers (2)

John Coleman
John Coleman

Reputation: 51998

By returning an anonymous function, you can do this in such a way that the resulting function can take an arbitrary function for input (although not in a very useful way):

fun id f = fn x => f x

This makes id a higher-order function which returns its input function unmodified. The type of id is fn : ('a -> 'b) -> 'a -> 'b

As an example of its "use":

- fun f x = x*x;
val f = fn : int -> int
- val g = id f;
val g = fn : int -> int
- g 5;
val it = 25 : int

A slightly more interesting example which will only work with functions of type 'a -> 'a:

 fun self_compose f = fn x => f (f x)

Upvotes: 0

sepp2k
sepp2k

Reputation: 370102

The one thing that you can do with a function that you can't do with any other value, is to call it. So using f2 as a function means calling it - that is, applying it to an argument.

So for example you could define f1 as:

fun f1 f2 = f2 42

and the inferred type of f1 would be (int -> 'a) -> 'a (making the type of f2 int -> 'a).

Upvotes: 2

Related Questions