Skip to content

Commit

Permalink
Monadic RPN calculator. Monadic composition.
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabi Volpe committed Aug 24, 2016
1 parent c276ed4 commit a5faf1d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
17 changes: 17 additions & 0 deletions category-theory/monadic-composition.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import Control.Monad

f = (+1) . (*100)
a1 = f 4

g = (\x -> return (x+1)) <=< (\x -> return (x*100))
a2 = Just 4 >>= g

f2 = foldr (.) id [(+1),(*100),(+1)]
b1 = f2 1

-- composition for the knight's quest
inMany :: Int -> KnightPos -> [KnightPos]
inMany x start = return start >>= foldr (<=<) return (replicate x moveKnight)

canReachIn :: Int -> KnightPos -> KnightPos -> Bool
canReachIn x start end = end `elem` inMany x start
31 changes: 31 additions & 0 deletions category-theory/rpn-monadic.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Control.Monad
import Data.List

readMaybe :: (Read a) => String -> Maybe a
readMaybe st = case reads st of [(x,"")] -> Just x
_ -> Nothing

a1 = readMaybe "1" :: Maybe Int
a2 = readMaybe "GO TO HELL" :: Maybe Int

foldingFunction :: [Double] -> String -> Maybe [Double]
foldingFunction (x:y:ys) "*" = return ((x * y):ys)
foldingFunction (x:y:ys) "+" = return ((x + y):ys)
foldingFunction (x:y:ys) "-" = return ((y - x):ys)
foldingFunction xs numberString = liftM (:xs) (readMaybe numberString)

b1 = foldingFunction [3,2] "*"
b2 = foldingFunction [3,2] "-"
b3 = foldingFunction [] "*"
b4 = foldingFunction [] "1"
b5 = foldingFunction [] "1 wawawawa"

solveRPN :: String -> Maybe Double
solveRPN st = do
[result] <- foldM foldingFunction [] (words st)
return result

c1 = solveRPN "1 2 * 4 +"
c2 = solveRPN "1 2 * 4 + 5 *"
c3 = solveRPN "1 2 * 4"
c4 = solveRPN "1 8 wharglbllargh"

0 comments on commit a5faf1d

Please sign in to comment.