简体   繁体   中英

What does () -> mean in ocaml?

I'm looking at this chunk 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?

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 this 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 the 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)...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM