试图从生成的列表中求和

时间:2014-03-12 12:53:14

标签: list haskell

你好,我最近开始研究Haskell,我正在尝试创建一个程序,给出一个函数,它创建一个列表,然后我想得到列表的总和:

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]]

我试图像这样得到列表的总和,但我总是得到错误

  *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]
你可以帮帮我吗?

1 个答案:

答案 0 :(得分:3)

my_sum接受一个参数,一个数字列表。由于my_list返回一个列表,将其结果包装在一个列表中会产生一个列表列表(不匹配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