Reputation: 6685
I'm new to Ocaml and I'm trying to figure out how this function works:
let ccc c1 c2 c3 = fun (s1, s2, s3) n ->
let (t1, r1) = (c1 s1 2) in
if r1 = 0
then let (t2, r2) = (c2 s2 n) in ((t1, t2, s3), r2)
else let (t3, r3) = (c3 s3 n) in ((t1, s2, t3), r3) ;;
c1, c2, c3
are all "choosers". I'm aware that the purpose of the function is to take 3 choosers in and let the first chooser pick which of the other two choosers to use, but I'm confused by the syntax. Could anyone explain please? Thank you!
Upvotes: 0
Views: 155
Reputation: 66823
It's hard to answer without knowing which part is confusing. Here are some simple examples that show some of the trickier parts.
# let f = fun x -> x + 1;;
val f : int -> int = <fun>
# f 3;;
- : int = 4
This defines f
as a function that adds one to an integer. The expression fun args -> expr
defines a function and the let
binds the function to the name f
.
# let f x = x + 1
val f : int -> int = <fun>
# f 3;;
- : int = 4
This defines the same function f. The meaning is exactly the same, it's just a slightly friendlier notation.
For whatever reason, your code is using both of these notations. I'm not sure I see a good reason to do this, but it does emphasize that if you pass three functions to ccc
you'll get a function back.
The other pieces are pretty straightforward (though maybe they take some getting used to):
Function calls are formed just by writing things next to each other:
c1 s1 2
c2 s2 n
c3 s3 n
These are just calls to c1
, c2
, and c3
.
Tuples are formed using commas (and conventionally parentheses also). So (t1, r1)
is a pair of values that is returned by the call to c1
.
I assume you understand if
/ then
/ else
, and let
in
. If not, they aren't hard to explain.
I'd actually suggest reading a tutorial on OCaml. It should be more efficient than asking questions one at a time on SO. There are good tutorials at ocaml.org.
Upvotes: 3