Using Haskell's map function to calculate the sum of a list

前端 未结 8 2041
太阳男子
太阳男子 2020-11-28 16:29

Haskell

addm::[Int]->Int
addm (x:xs) = sum(x:xs)

I was able to achieve to get a sum of a list using sum fu

8条回答
  •  借酒劲吻你
    2020-11-28 17:09

    Here it is, the supposedly impossible definition of sum in terms of map:

    sum' xs  =  let { ys = 0 : map (\(a,b) -> a + b) (zip xs ys) } in last ys
    

    this actually shows how scanl can be implemented in terms of map (and zip and last), the above being equivalent to foldl (+) 0 xs === last $ scanl (+) 0 xs:

    scanl' f z xs  =  let { ys = z : map (uncurry f) (zip ys xs) } in ys
    

    I expect one can calculate many things with map, arranging for all kinds of information flow through zip.

    edit: the above is just a zipWith in disguise of course (and zipWith is kind of a map2):

    sum' xs  =  let { ys = 0 : zipWith (+) ys xs } in last ys
    

    This seems to suggest that scanl is more versatile than foldl.

提交回复
热议问题