Unable to get type signature working for simple recursive function

Here is my code:

test :: (Num a) => [a] -> a
test []     = 0
test [x:xs] = x + test xs

But when I run it through ghci like :l test, I get this error:

[1 of 1] Compilation Main (test.hs, interpreted)

test.hs:3:7:
    Couldn't match type `a' with `[a]'
      `a' is a rigid type variable bound by
          the type signature for spew :: Num a => [a] -> a at test.hs:2:1
    In the pattern: x : xs
    In the pattern: [x : xs]
    In an equation for `spew': spew [x : xs] = x + spew xs
Failed, modules loaded: none.

Try not to laugh :) This is my first attempt at haskell. Any help or explanation would be great.

PS: I know that this can be easily done with a fold, but I try to write my own type signatures. Thanks in advance!

+5
source share
2 answers

You mean

test :: (Num a) => [a] -> a
test []     = 0
test (x:xs) = x + test xs -- note round brackets

with parentheses.

[x:xs]- this is a list with one element, the list itself, whereas (x:xs)- this is a list with the first element xand tail xs.

length (1:[1,1,1]), 4, length [1:[1,1,1]], 1 - - .

+8

, , :

test (x:xs) = ...

, [[b]], a == [b] test, xs [b], test xs b a test, , a == [a], :)

+5

All Articles