scala - Accessing the Accumulator & Element in `foldl` -
in scala's foldleft, know how access accumulator , element values in scala, not haskell.
i use foldleft find out, between 1 , 100, how many numbers have remainder of 1 when divided 3:
scala> list.range(1, 101).foldleft(0){ (acc, elem) => | if (elem % 3 == 1) acc + 1 | else acc | } res2: int = 33 how can same in haskell?
this direct translation of scala code haskell:
foldl (\acc x -> if x `mod` 3 == 1 acc + 1 else acc) 0 [1..100] in haskell, because of laziness of it, using foldl not idea, better choose foldl' or foldr, here foldr version:
foldr (\x acc -> if x `mod` 3 == 1 acc + 1 else acc) 0 [1..100]
Comments
Post a Comment