Fernando Rodriguez wrote:
data ConsCell a = Nil | Cons a (ConsCell a) deriving Show
head' Nil = Nothing
head' (Cons a _) = Just a
Works fine, however, what's wrong with the following function?
head'' | Nil = Nothing
| Cons a _ = Just a
You cannot use | as a general shortcut in function definitions as you
try here. The stroke is instead used to express different branches
selected by boolean expressions:
headIfNotZero Nil = Nothing
headIfNotZero (Cons a)
| a == 0 = Nothing
| otherwise = Just a
In this definition, (a == 0) and (otherwise) are boolean expressions.
GHCi, version 6.8.1: http://www.haskell.org/ghc/ :? for help
Loading package base ... linking ... done.
Prelude> otherwise
True
But in your definition of head'', Nil and (Cons a) are Patterns, not
boolean expressions, so it doesnt work out. If you don't like to write
out the name of the function you want to define over and over again, you
can use an explicit case statement:
head''' x = case x of
Nil -> Nothing
Cons a _ -> Just a
This is sometimes easier to read, but in this case, I would use your
head' definition.
Tillmann
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe