[Haskell-beginners] [x] and (x:_) for lists -- did you ever think that odd?
AntC
anthony_clayden at clear.net.nz
Sun May 20 23:14:15 CEST 2012
Think back to when you first came across Haskell ...
This, for example (from page 4 of the Gentle Intro -- my comments added):
length :: [a] -> Integer -- [ ] means list
length [] = 0 -- [] means list
length (x: xs) = 1 + length xs -- list, but no [ ]
Usually, showing a list uses square brackets and comma separators.
So list literals use square brackets and comma separators.
Type decls for a list uses square brackets.
List builders use square brackets and commas -- such as [1, 3 .. 9] or [0 ..]
Pattern matching for finite length lists use square brackets and commas:
f [] = ...
f [x] = ...
f [x, y] = ...
But pattern matching for unknown-length lists uses round brackets and colon --
such as that last binding for `length` above. And (nearly) every list-handling
function has a pattern for unknown-length lists.
Would this pattern matching seem less odd?:
head [x ..] = x
length [x, xs at ..] = 1 + length xs
Experienced Haskellers need not answer: you've got too used to ( : ) ;-)
AntC
More information about the Beginners
mailing list