Search code examples
pattern-matchingocamlconsreason

Where is Reason's cons (::) operator?


The cons (::) operator is a fundamental part of 1) writing recursive list functions in OCaml and similar languages, and 2) pattern matching on lists. However, I can't find anything in Reason's documentation concerning cons, and in the REPL, this throws an error:

Reason # let myList = [2, 3, 4];
let myList : list int = [2, 3, 4]
Reason # 1 :: myList;
Error: Syntax error

Is there a replacement for the cons operator?


Solution

  • Ah, it's aliased as the "immutable list append" operator in Reason's list of primitives:

    OCaml:

    1 :: 2 :: myList
    1 :: 2 :: [3, 4, 5]
    

    Reason:

    [1, 2, ...myList]
    [1, 2, ...[3, 4, 5]]
    

    Oddly, at least in the current version (0.0.6) you can use both syntaxes when pattern matching:

    let head = fun lst => switch lst {
      | [] => failwith "Empty list"
      | [hd, ...tl] => hd
    };
    
    let head = fun lst => switch lst {
      | [] => failwith "Empty list"
      | hd::tl => hd
    };