0
votes

I'm really new to Haskell and programming in general. I'm trying to add up the contents of a list without using the sum function from Data.List. Here's what I've got so far:

module Summ
    where
summ :: [Int] -> Int
summ xs = 
  if null xs == False
    then let y = x + (head xs)
         let xs = tail xs
    else print y

I'm pretty sure there's a lot wrong with this code, but for now the latest error is "parse error on input" for the else statement. What's wrong?

2
y is defined in the first branch of your expression, but used in the second half. What are you expecting to happen? - jkeuhlen
I was thinking that I could use y as sort of storage for the expressions I'm using to add up the elements of the list. I couldn't think of another way to do it... - VeganJoy
Take a look at Learn You a Haskell, it will walk you through basics of syntax and problem solving. - jkeuhlen
I've been teaching myself with that and @haskellbook, any other good resources? - VeganJoy
Remember that you're working in a purely functional language now. There's no such thing as "storage" or "variables" (at least, not in the usual sense). It's a huge adjustment to make, but in order to program efficiently in Haskell, you have to get used to that paradigm shift. - Silvio Mayolo

2 Answers

4
votes

The syntax for a let expression is let BINDINGS in EXPRESSION, e.g.

let x = 21 in x + x

It's probably complaining about else because it was expecting to see in.

There's a form of let without in, but that only works in do blocks (or list comprehensions).

4
votes

That doesn't look quite right to me. print returns IO (), which isn't Int, and the let section doesn't seem to lead up to an expression at all, and x wasn't defined. Were you attempting to write a recursive function?

summ [] = 0
summ (x:xs) = x + summ xs

The recursion isn't syntax; this simply uses two partial function definitions with pattern matching. One of them calls summ again, which is recursion, and eventually (given a finite list) that call will lead to the simpler, non-recursive function. The pattern also deconstructs the list into head and tail, so the function is equivalent to:

summ xs = if null xs
          then 0
          else head xs + summ (tail xs)

Note that both then and else branches are expressions of the same type.

Each of these definitions have type summ :: Num t => [t] -> t