Created
November 17, 2016 10:49
-
-
Save hatashiro/02ff29daf49e0f4da7ce3d8252d31d0d to your computer and use it in GitHub Desktop.
Some natural transformations
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
| {-# LANGUAGE ExistentialQuantification #-} | |
| {-# LANGUAGE Rank2Types #-} | |
| {-# LANGUAGE TypeOperators #-} | |
| module Main where | |
| -- | 'f ~> g' means natural transformation from a functor 'f' to a functor 'g' | |
| type (~>) f g = forall a. f a -> g a | |
| -- | const functor, which works as if it's just a constant | |
| data Const a b = Const a deriving Show | |
| instance Functor (Const a) where | |
| fmap _ (Const a) = (Const a) | |
| -- | natural transformation from list functor to const functor | |
| natLen :: [] ~> Const Int | |
| natLen = Const . length | |
| -- | natural transformation from list functor to maybe functor | |
| natHead :: [] ~> Maybe | |
| natHead [] = Nothing | |
| natHead (a:_) = Just a | |
| main :: IO () | |
| main = do | |
| print $ natLen [1 .. 100] -- Const 100 | |
| print $ natHead [1 .. 100] -- Just 1 | |
| print $ natHead ([] :: [Integer]) -- Nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment