Search code examples
listf#cons

No cons operator or curried cons function in F#?


We can write 3 + 4 or (+) 3 4 in F# and get the same result, and this works for most operators.

Why is it that the cons operator :: behaves differently? E.g. if I run

(::) 1 [2;3]

I get

error FS0010: Unexpected symbol '::' in expression

whereas I'd want to get [1;2;3].

On a related note, why is List.Cons not curried? Is there no built-in cons function of type 'T -> 'T list -> 'T list?


Solution

  • Actually (::) is not an operator. It's a union case. At least that's the way F# creators defined it:

    type List<'T> = 
       | ([])  :                  'T list
       | (::)  : Head: 'T * Tail: 'T list -> 'T list
    and 'T list = List<'T>
    

    Which makes sense: A list can be either empty or have a head and a tail.

    Regarding List.Cons I agree, it should have signature 'T->'T list ->'T list rather than 'T*'T List->'T list.