Skip to content

Instantly share code, notes, and snippets.

View monzou's full-sized avatar

Takuro Monji monzou

  • Tokyo
View GitHub Profile
import Control.Applicative
-- fmap : (a -> b) -> f a -> f b
-- fmap は関数とファクター値を引数にとって, 関数をファンクター値の中の値に適用
class Functor f where
fmap :: (a -> b) -> f a -> f b
-- <*> : f (a -> b) -> f a -> f b (f is Fanctor)
-- <*> は関数の入っているファンクター値と値の入っているファンクター値を引数にとって, ひとつ目のファンクターの中身の関数をふたつ目のファンクターの中身に適用
import Control.Applicative
-- <$> は fmap の中置関数
main = print $ filter (>50) $ (*) <$> [2, 5, 10] <*> [ 8, 10, 11 ] -- [ 55, 80, 100, 110 ]
@monzou
monzou / rpn.hs
Created June 30, 2012 07:01
逆ポーランド記法電卓
solveRPN :: String -> Double
-- solveRPN expression = head (fold foldingFunction [] (words expression)) をポインタフリースタイルで書いた ↓
solveRPN = head . foldl foldingFunction [] . words
where
-- foldingFunction stack operator
-- stack は x:y:ys に分割し, x と y を operator で評価してスタックの先頭を置き換える
foldingFunction (x:y:ys) "*" = (y * x):ys
foldingFunction (x:y:ys) "+" = (y + x):ys
foldingFunction (x:y:ys) "-" = (y - x):ys
foldingFunction (x:y:ys) "/" = (y / x):ys
-- Javascript っぽい真偽値判定型を定義する
class YesNo a where
yesno :: a -> Bool
instance YesNo Int where
yesno 0 = False
yesno _ = True
instance YesNo [a] where
yesno [] = False
-- 型クラス
-- Maybe 型を Eq 型クラスのインスタンスにする
instance (Eq m) => Eq (Maybe m) where
Just x == Just y = x == y
Nothing == Nothing = True
_ == _ = False
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show)
emptyNode :: a -> Tree a
emptyNode x = Node x EmptyTree EmptyTree
insert :: (Ord a) => a -> Tree a -> Tree a
insert x EmptyTree = emptyNode x
insert x (Node a left right)
| x == a = Node x left right
| x < a = Node a (insert x left) right
import qualified Data.Map as Map
data LockerState = Taken | Free deriving (Show, Eq)
type Code = String
type LockerMap = Map.Map Int (LockerState, Code)
lookupLocker :: Int -> LockerMap -> Either String Code
lookupLocker lockerNumber map = case Map.lookup lockerNumber map of
Nothing
-> Left $ "Locker " ++ show lockerNumber ++ " doesn't exist."
import Data.Char
import Data.List
main = print $ firstTo 40
digitSum :: Int -> Int
digitSum = sum . map digitToInt . show
firstTo :: Int -> Maybe Int
firstTo n = find (\x -> digitSum x == n) [ 1.. ]
import Data.Char
main = print $ decode 3 $ encode 3 "hello, world !"
encode :: Int -> String -> String
encode offset msg = map (\c -> chr $ ord c + offset) msg
decode :: Int -> String -> String
decode shift msg = encode (negate shift) msg
@monzou
monzou / word_count.hs
Created June 17, 2012 02:21
word-count @ Haskell
import Data.List
main = print $ wordCount "boom bip bip boom bang boom bang"
wordCount :: String -> [(String, Int)]
wordCount = map (\w -> (head w, length w)) . group . sort . words