[Haskell-cafe] Trouble with function with two clauses
Tillmann Rendel
rendel at rbg.informatik.tu-darmstadt.de
Wed Jan 9 13:44:42 EST 2008
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
More information about the Haskell-Cafe
mailing list