Domanda

When a function returns a function as result, let's say:

let func = function
| pat -> (function | pat -> x
                   | b -> y)

the two pat are not the same thing, the second pat can match to anything, so the last line is never reached. Any hint on how to solve this?

È stato utile?

Soluzione

If you want to express the second pat should be equal to the matched value against the first pat in your code, your code is wrong. It must be:

let func = function pat ->
  function 
    | pat' when pat = pat' -> x
    | b -> y

Pattern variables introduce new fresh variables and cannot refer to values bound to variables with the same name.

Altri suggerimenti

You should not use pattern matching just to test equality. You should use if then else. Your function is equivalent to:

let func a b if a = b then x else y

Using guards (the when part of camlspotter's answer) will work but is bad style (the caml compiler used to complain about it).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top