Question

I defined a higher-order function like this:

val func : int -> string -> unit

I would like to use this function in two ways:

other_func (func 5)
some_other_func (fun x -> func x "abc")

i.e., by making functions with one of the arguments already defined. However, the second usage is less concise and readable than the first one. Is there a more readable way to pass the second argument to make another function?

Was it helpful?

Solution

In Haskell, there's a function flip for this. You can define it yourself:

let flip f x y = f y x

Then you can say:

other_func (func 5)
third_func (flip func "abc")

Flip is defined in Jane Street Core as Fn.flip. It's defined in OCaml Batteries Included as BatPervasives.flip. (In other words, everybody agrees this is a useful function.)

OTHER TIPS

The question posed in the headline "change order of parameters" is already answered. But I am reading your description as "how do I write a new function with the second parameter fixed". So I will answer this simple question with an ocaml toplevel protocol:

# let func i s = if i < 1 then print_endline "Counter error."
    else for ix = 1 to i do print_endline s done;;
val func : int -> string -> unit = <fun>
# func 3 "hi";;
hi
hi
hi
- : unit = ()
# let f1 n = func n "curried second param";;
val f1 : int -> unit = <fun>
# f1 4;;
curried second param
curried second param
curried second param
curried second param
- : unit = ()
# 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top