-
-
Save toyboot4e/6f6c0464c1a941b28d3690a43f608d55 to your computer and use it in GitHub Desktop.
mapM と State モナドで mapAccumL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
短縮版ができた!!!!!