Created
August 13, 2013 16:11
-
-
Save puffnfresh/6222797 to your computer and use it in GitHub Desktop.
Partiality monad in Haskell using Free Maybe.
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
module Partiality where | |
import Control.Monad.Free | |
type Partiality = Free Maybe | |
never :: Partiality a | |
never = Free $ Just never | |
bad :: Partiality a | |
bad = Free Nothing | |
partialFromJust :: Maybe a -> Partiality a | |
partialFromJust (Just x) = Pure x | |
partialFromJust Nothing = Free Nothing -- bad | |
partialCollatz :: Int -> Int -> Partiality Int | |
partialCollatz x n | n == 1 = Pure x | |
| odd n = next $ 3 * n + 1 | |
| even n = next $ n `div` 2 | |
where next = Free . Just . partialCollatz (succ x) | |
partialRun :: Int -> Partiality a -> Maybe a | |
partialRun _ (Pure a) = Just a | |
partialRun _ (Free Nothing) = Nothing | |
partialRun 0 _ = Nothing | |
partialRun n (Free (Just p)) = partialRun (pred n) p |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment