Skip to content

Instantly share code, notes, and snippets.

View monzou's full-sized avatar

Takuro Monji monzou

  • Tokyo
View GitHub Profile
@monzou
monzou / SimpleCompressor.java
Created October 26, 2012 09:41
SimpleCompressor
package sandbox;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import org.apache.commons.io.IOUtils;
@monzou
monzou / sublime-tips.md
Created October 21, 2012 02:17
sublime text 2 memo

packages

  • gist
  • sidebar-enhancement
  • synced-sidebar
  • fild-diffs
  • local-history
  • surround
  • shell-turtlestein
  • convert2utf8
def qsort(seq)
return seq if seq.empty?
p = pivot(seq)
qsort(left(seq, p)) + [p] + qsort(right(seq, p))
end
def pivot(seq)
seq.sample
end
import Data.Ratio
import Data.List
import Control.Monad
--
-- 非決定性計算をしたい場合にモナドを使うと良い感じ
--
newtype Prob a = Prob { getProb :: [(a, Rational)] } deriving Show -- (3, 1%2) = 50 % の確率の 3
instance Functor Prob where
import Data.List
import Control.Monad
readMaybe :: (Read a) => String -> Maybe a
readMaybe st = case reads st of [(x, "")] -> Just x
_ -> Nothing
foldingFunction :: [Double] -> String -> Maybe [Double]
foldingFunction (x:y:ys) "*" = return ((y * x):ys)
foldingFunction (x:y:ys) "+" = return ((y + x):ys)
import Control.Monad.State
--
-- 普通に Stack
--
type Stack = [Int]
pop :: Stack -> (Int, Stack)
pop (x:xs) = (x, xs)
-- モナドは強化されたアプリカティブファンクタ−。
-- アプリカティブファンクターは文脈の付いた値に, 文脈を保ったまま普通の関数を適用させてくれる。
-- ただの 1 という値を文脈を持った Just 1 にしたりする関数は pure, 文脈を持った値に関数を適用するのが <*>
<*> :: (Applicative f) => f (a -> b) -> f a -> f b
(*) <$> Just 2 <*> Just 8 -- ((*) Just 2) -> Just 8
-- モナドは普通の値 a をとって文脈付きの値を返す関数に, 文脈付きの値 m a を渡すときに用いる。
import Data.Monoid
-- モノイドが便利なのはどんな場合?
-- 例えばふたつの文字列を引数に取り, その長さを比較して Ordering を返す。
-- 但し長さが等しい場合は文字列を辞書比較して返す。という関数を作りたい場合。
-- ふつうにつくるとこうなる
lengthCompare1 :: String -> String -> Ordering
lengthCompare1 x y = let
a = length x `compare` length y
@monzou
monzou / type.hs
Created July 7, 2012 07:36
type, newtype, data の違い
import Data.Monoid
-- type, newtype, data の違い
-- type : 型に別名を付けるもの
type IntList = [Int]
-- newtype : 型クラスのインスタンスを作りやすくするために既存の型を包んで新しい型をつくるもの
-- newtype は値コンストラクタとフィールドが 1 つだけという制限の付いた data 宣言だと見なしても良い。
-- 既存の型をある型クラスのインスタンスにしたい場合に使う。
newtype CharList = CharList { getCharList :: [Char] }
-- タプルの第一要素に fmap したいが, Functor は型引数を 1 つしか取れないので newtype を定義する
newtype Pair b a = Pair { getPair :: (a, b) } deriving (Show)
instance Functor (Pair c) where
fmap f (Pair (x, y)) = Pair (f x, y)
main = print $ fmap reverse(Pair ("foo", "bar")) -- Pair ("oof", "bar")