Skip to content

Instantly share code, notes, and snippets.

@josejuan
Created September 29, 2013 22:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josejuan/6757089 to your computer and use it in GitHub Desktop.
Save josejuan/6757089 to your computer and use it in GitHub Desktop.
import Prelude hiding (map)
-- Generalizar el mapeo (por ejemplo) consiste en definirlo
class Mappeable f where
map :: (a -> b) -> f a -> f b
-- Implementarlo para listas es directo
instance Mappeable [] where
map _ [] = []
map f (x:xs) = f x:map f xs
-- Si creamos nuestro tipo, por ejemplo un árbol binario
data Tree a = Leaf a | Node (Tree a) (Tree a) deriving Show
-- sería
instance Mappeable Tree where
map f (Leaf x) = Leaf (f x)
map f (Node l r) = Node (map f l) (map f r)
-- Así, cualquier función puede generalizar el mapeo,
-- ¡sobre cualquier tipo MAPPEABLE!, por ejemplo
sumar2 :: (Num a, Mappeable f) => f a -> f a
sumar2 = map (2+)
-- Entonces podemos usar dicha función GENERICA sobre cualquier
-- tipo Mappeable
test1 = sumar2 [1..5]
test2 = sumar2 (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 6) (Leaf 7)))
{-
*Main> test1
[3,4,5,6,7]
*Main> test2
Node (Node (Leaf 5) (Leaf 6)) (Node (Leaf 8) (Leaf 9))
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment