Skip to content

Instantly share code, notes, and snippets.

@ooharak
Created September 13, 2014 09:39
Show Gist options
  • Save ooharak/c2e9ab5e1552a009470b to your computer and use it in GitHub Desktop.
Save ooharak/c2e9ab5e1552a009470b to your computer and use it in GitHub Desktop.
Maybeとかリストの復習用日本語オレメモ
{- 学習用
復習として、Maybeやリストを改めて実装してみる.
本物と区別するために日本語を使う。
数学や情報科学の用語とあっていないのは気にしない。
大文字・小文字の区別がないと識別子として認識されないので
識別子の先頭はラテン文字にした
-}
import Control.Monad
-- Maybe a = Nothing | Just a
data Tたぶん a = K空 | J実 a
deriving Show
fromMaybe :: Maybe a -> Tたぶん a
fromMaybe Nothing = K空
fromMaybe (Just x) = J実 x
instance Monad Tたぶん where
-- return :: a -> Maybe a
return = J実
-- (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
x >>= f = case x of
K空 -> K空
J実 a -> f a
instance MonadPlus Tたぶん where
mzero = K空
a `mplus` b = case a of
K空 -> b
_ -> a
-- MaybeT
newtype T多分変換 m a = T多分変換
-- コンストラクタ引数兼アクセサ定義
{ runT多分変換 :: m (Tたぶん a) }
instance Monad m => Monad (T多分変換 m) where
-- return :: a -> MaybeT m a
return x = T多分変換 $ return $ J実 x
-- (>>=) :: MaybeT m a -> (a -> MaybeT m b) -> m b
x >>= f = T多分変換 $
-- t :: Maybe a
do t <- runT多分変換 x
case t of
K空 -> return K空
J実 a -> runT多分変換 $ f a
-- List a = Atom | Cons a (List a)
data R列 a = H端 | R連 a (R列 a)
x `s挿入` xs = R連 x xs
fromList [] = H端
fromList (x:xs) = s挿入 x $ fromList xs
instance Show a => Show (R列 a) where
show x = "<" ++ (show' x) ++ ">"
where
show' :: Show a => R列 a -> String
show' H端 = ""
show' (R連 x H端) = show x
show' (R連 x xs ) = (show x) ++ "," ++ show' xs
--map :: (a->b)->[a]->[b]
s写像 :: (a -> b) -> R列 a -> R列 b
s写像 f H端 = H端
s写像 f (R連 x xs) = R連 (f x) (s写像 f xs)
-- (++) :: [a]->[a]->[a]
g合体 :: R列 a -> R列 a -> R列 a
g合体 H端 y = y
g合体 (R連 x xs) y = R連 x (g合体 xs y)
-- concat :: [[a]] -> [a]
r連結 :: R列 (R列 a) -> R列 a
r連結 H端 = H端
r連結 (R連 x xs) = g合体 x (r連結 xs)
instance Monad R列 where
return x = R連 x H端
x >>= f = r連結 $ s写像 f x
instance MonadPlus R列 where
mzero = H端
mplus = g合体
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment