我怎样才能制作一个与此类似的函数,但它n
是一个以 xs 的长度值开头1
和结尾的数字的变量?
例如,我想[1,2,3]
返回3*1 + 2*2 + 1*3
.
function :: [Int] -> Int
function xs = foldr (\x acc -> (x*n) + acc) 0 xs
我怎样才能制作一个与此类似的函数,但它n
是一个以 xs 的长度值开头1
和结尾的数字的变量?
例如,我想[1,2,3]
返回3*1 + 2*2 + 1*3
.
function :: [Int] -> Int
function xs = foldr (\x acc -> (x*n) + acc) 0 xs
一个惯用的 Haskell 答案可以是:
function = sum . zipWith (*) [1 ..] . reverse
从右到左阅读:你反转列表(reverse
),这样做你不需要倒数(从 n 到 1)而是向前(1 到 n)zipWith (*) [1..]
...最后总结一下(sum
)。
使用zipWith
:
import Data.List
function :: [Int] -> Int
function xs = sum $ zipWith (*) xs lst
where
lst = unfoldr (\x -> Just (x-1,x-1)) $ (length xs) + 1
main = putStr $ show $ function [40,50,60]
function xs = fst $ foldr (\x (acc,n) -> (x*n+acc,n+1)) (0,1) xs
或者也许更具可读性:
function = fst . foldr f (0,1) where f x (acc,n) = (x*n+acc, n+1)