Haskell多个参数函数

时间:2016-06-08 06:36:48

标签: haskell

myfunc:: [Int] -> Int -> Int   
myfunc mylist i =
    if length(mylist) == 0 then 1

    else
       (head(mylist) * i) +  myfunc((tail(mylist)) (i+1))

我希望在列表中获得加权总和。

例如,在给定参数[10,9,8,7,6]1处, 我想得到10*1 + 9*2 + 8*3 + 7*4 + 6*5 ..

但我的代码错误

test.hs:9:18: error:
    • Couldn't match expected type ‘Int’ with actual type ‘Int -> Int’ 

如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

你应该检查你的括号 - 你需要使用更多的它们(导致这里的问题)

如果您查看myfunc((tail(mylist)) (i+1)),那么如果算上(..),您会看到此处myfunc的一个参数是tail(mylist) (i+1),但这意味着您尝试将(i+1)应用于tail(mylist)

除了使用lengthhead进行检查外,您还可以使用模式匹配。

这是您的功能的清理版本:

myfunc :: [Int] -> Int -> Int   
myfunc [] _ = 1
myfunc (h:tl) i = h*i + myfunc tl (i+1)

将为您的示例返回111

> myfunc [10,9,8,7,6] 1
111

我不知道您对Haskell的看法有多少,但您可以将其表达为

myfunc :: [Int] -> Int -> Int   
myfunc weights start = 1 + sum (zipWith (*) weights [start..])

也是 - 我认为更具可读性和惯用性

另外: - 如果列表为空,为什么1?如果列表为空,那么你的加权是不是0

相关问题