2

我怎样才能制作一个与此类似的函数,但它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
4

3 回答 3

9

一个惯用的 Haskell 答案可以是:

function = sum . zipWith (*) [1 ..] . reverse

从右到左阅读:你反转列表(reverse),这样做你不需要倒数(从 n 到 1)而是向前(1 到 n)zipWith (*) [1..]...最后总结一下(sum)。

于 2013-06-27T11:38:11.137 回答
5

使用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]
于 2013-06-27T04:31:14.217 回答
2
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)
于 2013-06-27T08:04:15.313 回答