简体   繁体   中英

OCaml - Give a function of type (int -> int) -> int

I'm completely lost on this. It was explained that functions are right justified so that let add xy = x + y;; has a function type of int -> int -> int or int -> (int -> int) .

I'm not sure how I'd define a function of type (int -> int) -> int . I was thinking I'd have the first argument be a function that passes in an int and returns an int . I've tried:

let add = fun xy -> x + y --- int -> int -> int

let add = fun fx = (fx) + 3 --- ('a -> int) -> 'a -> int

What about

let eval (f: int -> int) :int = f 0

?

fun x -> (x 1) + 1;;
- : (int -> int) -> int = <fun>

or

let foo f = (f 1) + 1;;
val foo : (int -> int) -> int = <fun>

it works like

foo (fun x -> x + 1);;
- : int = 3

Your questions is highly associated with the notion of Currying .

But before that, let me say that if you want to write a function that needs a parameter to be a function, you could declare a normal function, and just use its parameter like a function. No need to complicate it. See the ex:

let f x = x(10) + 10

Now comes the currying part. In OCaml, the parameters are semantically evaluated just one at a time, and after evaluating an argument, an anonymous function is returned. This is important because it lets you supply part of the arguments of a function, creating effectively a new function (which is called Partial Application).

In the example bellow, I use + as a function (parenthesis around an operator turn it to a normal function), to create an increment function. And apply it to the previous f function.

let incr = (+) 1
f incr

The code evaluates to f incr = incr(10) + 10 = 21

This link has more information on the topic applied to OCaml.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM