Thursday, 12 September 2013

Haskell Function To Add First Two Numbers Of List

Haskell Function To Add First Two Numbers Of List

I am attempting to write a function so that it can find the first two
elements of a list, add them, and then place them at the head of the list.
However I am running into unexpected errors when I try to do so.
Code:
command :: Operation -> [Int] -> [Int]
command Plus [x] = error "Not enough to conduct a plus operation"
command Plus (x:xs) = x + head(xs) : [xs]
The first function for the single element list works just fine, however
the second one where the actual operation should occur does not. I thought
it would take that the x off the list, then take the following element
using head(xs), thus the first two off the list are available, add them
and then put them in the front of the list as I wanted.
When I run it over command Plus [4,5,6] I should get [9,6] However I get
this error:
Couldn't match expected type `Int' with actual type `[Int]'
In the expression: xs
In the second argument of `(:)', namely `[xs]'
In the expression: (x + head (xs)) : [xs]
Failed, modules loaded: none.
If anyone can give me some insight, I'd really appreciate it!

No comments:

Post a Comment