haskell foldr和变量

时间:2013-06-27 04:16:10

标签: function haskell functional-programming fold

如何创建与此类似的函数,但n是一个变量,其数字以1开头,以xs的长度值结束?

例如,我希望[1,2,3]返回3*1 + 2*2 + 1*3的结果。

function :: [Int] -> Int
function xs = foldr (\x acc -> (x*n) + acc) 0 xs

3 个答案:

答案 0 :(得分:9)

惯用的Haskell答案可以是:

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

从右到左阅读:你反转列表(reverse),这样做你不需要向后计数(从n到1)而是向前计数(从1到n)...然后你拉链索引使用*(zipWith (*) [1..]),最后总结(sum)。

答案 1 :(得分: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]

答案 2 :(得分: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)