我需要对数字列表进行平方并将其除以列表的平均值。到目前为止我有:
square :: Float -> Float
square x = x * x
s2 :: [Float] -> Float
s2 xs = map square (map (\c -> c - mean) xs)
任何帮助都会非常准确。
答案 0 :(得分:0)
问题尚不清楚,但我假设您的意思是将平方的和除以平均值。简单版本:
sumOfSquaresOverMean :: Fractional a => [a] -> a
sumOfSquaresOverMean as = sum (map (^2) as) / mean as
mean :: Fractional a => [a] -> a
mean as = sum as / fromIntegral (length as)
这确实存在一个缺点,即列表将被遍历三次。 Gabriel Gonzalez的"Composable Streaming Folds"讨论了一个可能的解决方案,但它更先进,所以你现在可能想跳过它。
答案 1 :(得分:-1)
s2 :: [Float] -> Float
s2 xs = sum $ map ((/mean).(^2)) xs
where mean= sum xs / fromIntegral (length xs)
测试:
λ: s2 [1.0, 2.0, 3.0]
7.0