Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@toyboot4e
Last active November 30, 2022 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toyboot4e/6f6c0464c1a941b28d3690a43f608d55 to your computer and use it in GitHub Desktop.
Save toyboot4e/6f6c0464c1a941b28d3690a43f608d55 to your computer and use it in GitHub Desktop.
mapM と State モナドで mapAccumL
#!/usr/bin/env stack
import Control.Monad.State
import Data.List
import Data.Tuple
myMapAccumL :: (Int -> Int -> (Int, Int)) -> Int -> [Int] -> (Int, [Int])
myMapAccumL f s0 xs =
swap
$ runState
( mapM
( \x -> do
acc <- get
let (acc', x') = f acc x
put acc'
return x'
)
xs
)
s0
-- ([1, 2, 3], 6)
main :: IO ()
main = do
-- (6, [1,2,3])
print $ mapAccumL (\acc x -> (acc + x, x)) (0 :: Int) [1, 2, 3]
-- (6, [1,2,3])
print $ myMapAccumL (\acc x -> (acc + x, x)) (0 :: Int) [1, 2, 3]
@toyboot4e
Copy link
Author

toyboot4e commented Nov 30, 2022

短縮版ができた!!!!!

#!/usr/bin/env stack

import Control.Monad.State
import Data.List

main :: IO ()
main = do
  -- ([1,2,3], 6)
  print $ runState (mapM (\x -> state $ \acc -> (x, x + acc)) [1, 2, 3]) (0 :: Int)

  -- ([1,3,6], 6): 数列 → 累積和
  print $ runState (mapM (\x -> state $ \acc -> (x + acc, x + acc)) [1, 2, 3]) (0 :: Int)

  -- ([1,2,3], 6): 累積和 → 数列
  print $ runState (mapM (\x -> state $ \last -> (x - last, x)) [1, 3, 6]) (0 :: Int)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment