genesisxyz
genesisxyz

Reputation: 798

OCaml - How do I create a function with a function as output?

"Write a function lv: cfg -> (blabel -> ide set), which computes the live variables analysis on the given control flow graph."

Having cfg and blabel defined and ide set as a list of string, how can I create a function with that signature?

Upvotes: 1

Views: 765

Answers (1)

You're presumably familiar with the let syntax to define a function:

let f x = x + 1 in …

You can use this syntax anywhere, including in a function body. Now if you happen to use the inner function's name as the return value of the outer function, the outer function will be returning a function.

let outer_function x =
  let inner_function y = x + y in
  inner_function

The let syntax is in fact syntactic sugar for fun or function. In particular, if you define inner_function just to use the name once, you might as well use the fun notation and not bother giving the inner function a name.

let outer_function x =
  fun y -> x + y

Furthermore, if all the outer function does when you pass it an argument is to build and return an inner function, then consider its behavior when you pass that function two arguments. First the outer function builds an inner function, using its first (and only) argument; then that inner function is applied to the second argument, so its body is executed. This is equivalent to having just one function that takes two arguments. This observation is known as currying.

let outer_function x y = x + y

Note that the type of this function is int -> int -> int; this is the same type as int -> (int -> int) (the arrow type operator is right-associative).

Currying doesn't apply when the outer function does some work before building the inner function. In that case, the work is performed after receiving the first argument.

let outer_function x =
  print_endline "outer";
  fun y -> print_endline "inner"; x + y

So the structure of your code is likely to look like this:

let lv (c : cfg) : blabel -> ide set =
  let c' = do_some_precomputation c in
  fun (bl : blabel) -> (… : ide set)

Upvotes: 5

Related Questions