问题描述
我正在尝试使用以下代码在haskell中编写“平均”定义,以便 函数产生输入中所有元素的平均值(均值) 采集。这是我到目前为止所拥有的:
> type RunningTotal = (Sum Float,Sum Float)
> getAverage :: RunningTotal -> Float
> getAverage (_,0) = 0
> getAverage (total,count) = getSum total / getSum count
> average :: Foldable f => f Float -> Float
> average = getAverage . foldMap (\ Sum x -> [Sum x])
我得到了错误:
In the pattern: Sum
The lambda expression ‘\ Sum x -> ...’ has two arguments,but its type ‘Sum t0 -> RunningTotal’ has only one
In the second argument of ‘(.)’,namely ‘(\ Sum x -> [Sum x])’
但是如果我重复一遍,使用相同的参数,我会得到:
• The constructor ‘Sum’ should have 1 argument,but has been given none
• In the pattern: Sum
In the expression: \ Sum x -> [Sum x]
In the second argument of ‘(.)’,namely
‘(\ Sum x -> [Sum x],\ Sum x -> [Sum x])’
我在做什么错? 除了最后一行中的括号,请不要进行其他任何更改。
解决方法
foldMap
的参数的类型应为Float -> RunningTotal
。您首先给定的(\ Sum x -> [Sum x]
)的lambda有一个语法错误:您可能是指\(Sum x) -> [Sum x]
(您给出的版本是带有两个参数的lambda,其中第一个名为{{ 1}}和第二个Sum
)。此更正的lambda类型为x
,这不是您想要的类型。
正确的lambda是Sum a -> [Sum a]
。
您的函数propertiesMap.forEach((key,value) -> System.out.printf("%s=%s%n",key,value));
现在具有2个参数-\ Sum x -> [Sum x]
和Sum
。您可以将其修复为x
甚至\(Sum x) -> [Sum x]
。