diff --git a/category-theory/monadic-composition.hs b/category-theory/monadic-composition.hs new file mode 100644 index 0000000..2ddceb6 --- /dev/null +++ b/category-theory/monadic-composition.hs @@ -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 diff --git a/category-theory/rpn-monadic.hs b/category-theory/rpn-monadic.hs new file mode 100644 index 0000000..62e4be8 --- /dev/null +++ b/category-theory/rpn-monadic.hs @@ -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"