Skip to content

Instantly share code, notes, and snippets.

@puffnfresh
Created August 13, 2013 16:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save puffnfresh/6222797 to your computer and use it in GitHub Desktop.
Save puffnfresh/6222797 to your computer and use it in GitHub Desktop.
Partiality monad in Haskell using Free Maybe.
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