1

I am having trouble with some haskell code. Namely a function checksum which is meant to check whether the sum of a list of Integers is equal to the Integer argument tot.

There is something wrong with the syntax because I keep getting:

Main.hs:11:1: Parse error in pattern: checksum

And the module isn't loaded.

checksum :: ([Int], Int) -> (Bool, Int)

checksum [x] tot
    | x == tot        = (True, tot)
    | otherwise       = (False, tot)

checksum x:xs tot = checksum xs tot-x`
watson
  • 43
  • 6

2 Answers2

2

In Haskell, function application has a higher associative strength than any other operation.

So, the pattern checksum x:xs tot is parsed as (checksum x):(xs tot), which doesn't make any sense as a pattern, and causes a parse error. Specifically, patterns don't allow function applications, such as (checksum x), except for defining functions at the top level.

As the comment says, you should parenthesize it as checksum (x:xs) tot so it will parse as you expect, defining checksum at the top level.

comingstorm
  • 25,557
  • 3
  • 43
  • 67
1

Ok, a number of corrections to make this work. I am going on the assumption that your type annotation is correct.

checksum :: ([Int], Int) -> (Bool, Int)

checksum ([x], tot) -- make argument a single tuple
    | x == tot        = (True, tot)
    | otherwise       = (False, tot)

checksum ((x:xs), tot) = checksum (xs, tot-x) -- group list; make argument and result a tuple.
-- removed extraneous back-tick at the end of the last line.
John F. Miller
  • 26,961
  • 10
  • 71
  • 121