jueves, 15 de octubre de 2015

Mónadas en Haskell


---De una explicación preliminar de mónadas en Haskell
import Control.Monad
--- data Maybe t = Just t | Nothing


add :: Maybe Int -> Maybe Int -> Maybe Int
add mx my =
  case mx of
    Nothing -> Nothing
    Just x  -> case my of
                 Nothing -> Nothing
                 Just y  -> Just (x + y)

sol n =
    case n of
      2 -> 3
      4 -> 4
      5 -> 6
      _ -> 10

sol2 2 = 3
sol2 4 = 4
sol2 6 = 6
sol2 _ = 10

sol3 n | n== 2 = 3
           | n==4  = 4
           | n==5  = 6
           | otherwise = 10

add2 :: Maybe Int -> Maybe Int -> Maybe Int
add2 mx my =      
    -- Adds two values of type (Maybe Int), where each input value can be Nothing
  mx >>= (\x ->
      -- Extracts value x if mx is not Nothing
    my >>= (\y ->
     -- Extracts value y if my is not Nothing
      return (x + y)))
 -- Wraps value (x+y), returning the sum as a value of type (Maybe Int)

add3 :: Maybe Int -> Maybe Int -> Maybe Int
add3 mx my = do
  x <- mx
  y <- my
  return (x + y)

add4 :: Maybe Int -> Maybe Int -> Maybe Int
add4 = liftM2 (+)

con4 :: Maybe String -> Maybe String -> Maybe String
con4 = liftM2 (++)

No hay comentarios:

Publicar un comentario