Created
August 19, 2009 10:17
-
-
Save jsoffer/170276 to your computer and use it in GitHub Desktop.
Monads: bind/return
This file contains hidden or 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
-- Uso de "bind" | |
import Data.List.HT (chop) | |
import Control.Monad(liftM, foldM) | |
lineas :: IO ([[String]]) | |
lineas = | |
(liftM -- (String -> [[String]]) -> (IO (String) -> IO ([[String]])) | |
((map (chop (== ','))).lines)) -- String -> [[String]] | |
. readFile -- IO (String) | |
$ "triangles.txt" | |
>>= | |
return -- [[String]] -> IO ([[String]]); en realidad así no hace absolutamente nada | |
-- lineas2 :: IO ([[String]]) | |
-- lineas2 :: IO ([[Integer]]) | |
lineas2 :: IO ([Integer]) | |
lineas2 = | |
readFile "triangles.txt" -- IO (String) | |
>>= | |
(\k -> return (lines k)) -- String -> IO ([String]) | |
>>= | |
(\k -> return (map (chop (== ',')) k)) -- [String] -> IO ([[String]]) | |
>>= | |
(\k -> return $ (map $ map $ (filter (/= '\r'))) k) -- [[String]] -> IO ([[String]]) | |
>>= | |
(\k -> return $ (map $ map read) k) -- [[String]] -> IO ([[Integer]]) | |
>>= | |
(\k -> return $ map sum k) -- [[Integer]] -> IO ([Integer]) | |
-- lo mismo que lineas2, con composición para evitar lambda | |
lineas3 :: IO ([Integer]) | |
lineas3 = | |
readFile "triangles.txt" >>= | |
return.lines >>= | |
return.(map (chop (== ','))) >>= | |
return.(map $ map $ (filter (/= '\r'))) >>= | |
return.(map $ map read) >>= | |
return.(map sum) | |
-- todo junto | |
lineas4 :: IO ([Integer]) | |
lineas4 = | |
liftM ((map sum) . | |
(map $ map read) . | |
(map $ map $ (filter (/= '\r'))) . | |
(map (chop (== ','))) . | |
lines) $ readFile "triangles.txt" | |
operacion :: IO (Integer) | |
operacion = | |
return [1..10] -- IO ([Integer]) | |
>>= | |
(foldM (\ j k -> return (10*(j+k))) 1) -- [Integer] -> IO (Integer) | |
pares :: IO ([Integer]) | |
pares = | |
return [1..10] -- IO ([Integer]) | |
>>= | |
(\k -> return (filter even k)) -- [Integer] -> IO ([Integer]) | |
{- | |
http://projecteuler.net/project/triangles.txt | |
% -> head triangles.txt | |
-340,495,-153,-910,835,-947 | |
-175,41,-421,-714,574,-645 | |
-547,712,-352,579,951,-786 | |
419,-864,-83,650,-399,171 | |
-429,-89,-357,-930,296,-29 | |
-734,-702,823,-745,-684,-62 | |
-971,762,925,-776,-663,-157 | |
162,570,628,485,-807,-896 | |
641,91,-65,700,887,759 | |
215,-496,46,-931,422,-30 | |
-} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment