I'm looking at this chun of code (the first 2 lines are pseudo code for context)
typ = Void | Bool | Int
type bind = typ * string
let check_binds (kind : string) (binds : bind list) =
List.iter (function
(Void, b) -> raise (Failure ("illegal void " ^ kind ^ " " ^ b))
| _ -> ()) binds;
So what I think is happening is that there is a list called binds
, and because of iter
, the function defined inside the parentheses after "List.iter
" is being applied to every item in binds
.
However I'm confused about the function itself. Here's my attempt at trying to write out the function individually
function
(Void, b) -> raise (Failure ("illegal void " ^ kind ^ " " ^ b)
| _ -> ()
What does _ -> ()
mean?
CodePudding user response:
This is an anonymous function definition using pattern-matching with 2 clauses:
- 1st one covers the case
(Void, b)
- 2nd one covers "everything else":
_
in a pattern matching is a catch-all branch that matches anything.
And when the latter branch is matched in your snippet the function will just return ()
- which is the only possible value of type unit
.
So this lambda function is a kind of validator that raises an error if you have a value with a wrong type (Void parametrized by anything) and does nothing (returns a unit) in other cases. And honestly, this looks like a hack that tries to mitigate the sub-optimal types design - I'm quite sure we can do better and make (Void, b)
unrepresentable state (but this is orthogonal to what was asked)...