开发者

ocaml null keyword: once but no more?

At the ocaml toplevel (version 3.11.2), this simple expression is giving me an error:

# let a = [] in if null a then 0 else 1;;
Error: Unbound value null

I have just started learning ocaml from the oreilly book, which seems to use null as a keyword frequently - for example, top of page 32:

# let rec size a_list =
    if null a_list then 0
    else 1 + (size 开发者_运维百科(List.tl a_list));;

I'm embarrassed to ask such an obviously googleable question here. But after much googling I came up empty-handed. So I'm as open to google query suggestions as I am to straightforward answers. (failed google attempts: [ocaml "Error: Unbound value null"] [ocaml null keyword] [ocaml changelog null] [ocaml change null] ).

Question: was null once an ocaml keyword, but no longer? Or did I install ocaml wrong or misspell something?

I can of course replace every occurrence of "null" with "[ ]" in code, but I'm surprised that a verbatim copy of code from a book gives me an error so early. Is this book full of other gotchas? I believe it was written with ocaml 2.04 in mind; is that too old? I chose it because I liked the TOC and the free availability online. Other than this null error (which I am still more ready to blame on myself than on the authors), the explanations are nice and I'm looking forward to the discussion of mixing functional & imperative style (mind-expanding for me, as someone only familiar with c/c++).


null is defined in the book on page 31. It's a normal function that you can define yourself:

let null l = (l = [])

This nomenclature is more or less based on Lisp, where NIL is an empty list (also written as ()) and NULL is a predicate (a function returning true or false), exactly like null above.


OCaml provides powerful Pattern Matching, which allows you to define the function more readably:

let rec size a_list = match a_list with
 | [] -> 0
 | _ :: tl -> 1 + (size tl)

As pattern matching is often performed on the last argument, a special notation is available:

let rec size = function
 | [] -> 0
 | _ :: tl -> 1 + (size tl)

null could be defined shorter by using (=) (i.e., the test for equality as a normal/prefix function):

let null = (=) []
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜