JmRag
JmRag

Reputation: 1459

Trying to sum from a generated list

Hello I recently started studying Haskell and I am trying to make a little program that given a function it creates a list and then I want to take the sum of the list:

f a b c = a+b+c

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

my_list f a b c = [f a b x |x <- [1..c]]

I am trying to take the sum of the list like this but I always get errors

  *Main> my_sum [my_list f 1 1 4]

<interactive>:13:1:
    No instance for (Num [t0]) arising from a use of `my_sum'
    Possible fix: add an instance declaration for (Num [t0])
    In the expression: my_sum [my_list f 1 1 4]
    In an equation for `it': it = my_sum [my_list f 1 1 4]

<interactive>:13:9:
    No instance for (Num t0) arising from a use of `my_list'
    The type variable `t0' is ambiguous
    Possible fix: add a type signature that fixes these type variabl
    Note: there are several potential instances:
      instance Num Double -- Defined in `GHC.Float'
      instance Num Float -- Defined in `GHC.Float'
      instance Integral a => Num (GHC.Real.Ratio a)
        -- Defined in `GHC.Real'
      ...plus three others
    In the expression: my_list f 1 1 4
    In the first argument of `my_sum', namely `[my_list f 1 1 4]'
    In the expression: my_sum [my_list f 1 1 4]

can you help me?

Upvotes: 0

Views: 94

Answers (1)

Andr&#225;s Kov&#225;cs
Andr&#225;s Kov&#225;cs

Reputation: 30103

my_sum takes one argument, a list of numbers. Since my_list returns a list, wrapping its result in a list results in a list of lists (mismatching my_sum):

my_sum [my_list f 1 1 5] -- argument has type Num a => [[a]]
my_sum (my_list f 1 1 5) -- this is right 

Upvotes: 3

Related Questions