2

How can I make a function similar to this but with n being a variable with a number beginning in 1 and ending with the value of the length of xs?

For Example I want [1,2,3] to return the result of 3*1 + 2*2 + 1*3.

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

3 Answers 3

9

A idiomatic Haskell answer can be:

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

Reading from right to left: you reverse the list (reverse), doing so you won't need to count backward (from n to 1) but forward (1 to n)... then you zip it with the index using * (zipWith (*) [1..]) and finally sou sum things up (sum).

Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible that Rance wanted a less general solution, like this: "function n = sum . zipWith (*) [1 .. ] . reverse $ take n [1 ..]" ?
According to the signature he gave for function, I don't think so.
btw, it's easier to write [1 .. n] rathern than take n [1 ..] ;)
5

Using 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]

1 Comment

If I understand the question right, function [40,50,60] should result in 3*40 + 2*50 + 1*60, and not in 60*40+50*50+40*60.
2
function xs = fst $ foldr (\x (acc,n) -> (x*n+acc,n+1)) (0,1) xs

Or maybe more readable:

function = fst . foldr f (0,1) where f x (acc,n) = (x*n+acc, n+1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.