[<<][compsci][>>][..]
Fri Apr 6 11:35:38 CEST 2012

Why are "stateful maps" not part of standard functions?

Meaning:  (s,a) -> (s,b) -> [a] -> (s, [b])

Maybe this is because it's more easily handled in the state monad, in
combination with forM?   I'm not convinced, compare:

  test = flip runState 0 $ do
    forM [1..10] $ (\i -> do
                       s <- get
                       put $ s + 1
                       return $ i + s)


With:

  -- foldr with output stream
  foldo :: (a -> s -> (s, b)) -> s -> [a] -> (s, [b])
  foldo f = fld where
    fld s [] = (s, [])
    fld s (a:as) = (s, b:bs) where
      (s',  b)  = f a s
      (s'', bs) = fld s' as

  test1 = foldo (\a s -> (s+1, a+s)) 0 [1..10]

Why is 'foldo' not a standard library function?  Actually, it is! [1]


  mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
  mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])

[1] http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-List.html





[Reply][About]
[<<][compsci][>>][..]