开发者

Ocaml, understand a function

I have some problems in understanding how this开发者_高级运维 function works, in particular I' don't understand the control flow of itregarding the last line. Can someone explain me the steps it does, maybe with a pseudocode?

    let traduit_pair a b =
            let a = traduit mark a in let b = traduit mark b in (a, b) in
    let (teq1, teq2, lneq) =
            let rec f l1 l2 l3 =
            (function
                 | [] -> ((Uplet l1), (Uplet l2), l3)
                 | EqualIF (a, b) :: fin ->
                     let (a, b) = traduit_pair a b
                     in f (a :: l1) (b :: l2) l3 fin
                 | NotEqualIF (a, b) :: fin ->
                         let (a, b) = traduit_pair a b
                     in f l1 l2 ((a, b) :: l3) fin)
            in f [] [] [] (List.rev condlst)


The general flow of your code is like this:

First the function traduit_pair is defined. It takes two arguments a and b and returns a pair containing the result of applying traduit mark to each of them.

Then the variables teq1, teq2 and lneq are defined to each contain one element of the triple returned by f [] [] [] (List.rev condlst), where f is defined as follows:

First of all let's look at why f can be called with four arguments when its definition only names three arguments: As you probably know ML allows curried function definitions and the definition let f x y = blabla is really just a shortcut for let f = fun x => fun y => blabla.

So when we talk about a function taking two arguments, we're really talking about a function taking one argument and returning another function which takes another argument. Likewise a function which takes three arguments and then returns another function taking another argument, is the same thing as a function taking four arguments.

The function keyword which is used in the definition of f is a syntactic shortcut to create a function taking an argument and pattern matching on it. That is to say function | p1 -> e1 | p2 -> e2 is a shortcut for fun x => case x of | p1 -> e1 | p2 -> e2. So let rec f l1 l2 l3 = function | p1 -> e1 | p2 -> e2 is the same as let rec f l1 l2 l3 = fun l4 => case l4 of | p1 -> e1 | p2 -> e2, which is the same as let rec f l1 l2 l3 l4 = case l4 of | p1 -> e1 | p2 -> e2, which is easily identifiable as a function taking four arguments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜