Haskell: Parse error in pattern

user905686 picture user905686 · Dec 19, 2011 · Viewed 27.3k times · Source

Who likes to tell me what is wrong with this code (syntactically)?

-- merge two sorted lists
mergeX [] b res = b ++ res
mergeX a [] res = a ++ res
mergeX a:as b:bs res
    | a > b     = mergeX as b:bs a:res
    | otherwise = mergeX a:as bs b:res

Interpreter:

Parse error in pattern: mergeX

Answer

kennytm picture kennytm · Dec 19, 2011

You need some parenthesis:

mergeX [] b res = b ++ res
mergeX a [] res = a ++ res
mergeX (a:as) (b:bs) res
    | a > b     = mergeX as (b:bs) (a:res)
    | otherwise = mergeX (a:as) bs (b:res)

The reason is because : has a lower precedence than function application, so mergeX a:as b:bs res will be parsed as:

(mergeX a):(as b):(bs res)

which is an error.