はじめから少しずつ
コレからのHaskell勉強法を見直す.とりあえずHaskellに書いてある事を殆ど理解できたら,遊ぼうと思う.先ずはSyntaxから攻めて行くぞ.
As-patterns
@の右側を,@の左側に割り当てる.
hoge z y@(x:xs) = z:x:x:x:y
hugsで実行.
Main> hoge 'G' "ooool" "Goooooool"
へぇ.いつかきっと役に立つさ.
classes
オブジェクト指向のクラス?かと思いきや,descripthinに何も書いてない.http://221.112.61.214/~kzk/column/haskell_type.htmlを見て,へぇぇ.
とりあえず,こんなのを書いた.
class Hoge a where (+++) :: [a] -> [a] -> [a] instance Hoge Integer where a@(x:xs) +++ b@(y:ys) = zipWith (+) a b instance Hoge Char where a@(x:xs) +++ b@(y:ys) = a ++ b
hugsで実行.
Main> (+++) [(1::Integer),(2::Integer)] [(3::Integer),(4::Integer)] [4,6] Main> (+++) "Stadium " "Arcadium" "Stadium Arcadium"
結構面白いなぁ.ただ,(1::Integer)って記法はどーにかならないかな.
data
descripthinを直訳すると,Haskellでの型を定義するってことか.Cの構造体みたいなものか?
data UBT = U [Integer] [Integer] | B [Integer] [Integer] [Integer] | T [Integer] [Integer] [Integer] [Integer] hoge :: UBT -> [Integer] hoge (U a@(w:ws) b@(x:xs)) = zipWith (+) a b hoge (B a@(w:ws) b@(x:xs) c@(y:ys)) = zipWith (+) (zipWith (+) a b) c hoge (T a@(w:ws) b@(x:xs) c@(y:ys) d@(z:zs)) = zipWith (+) (zipWith (+) (zipWith (+) a b) c) d
何としても@を使いたい.てか,こうすると[1]でも[1,2]でもちゃんと渡せるので楽だと思った.
hugsで実行.
Main> hoge (U [1,2,3] [4,5,6]) [5,7,9] Main> hoge (B [1,2,3] [4,5,6] [7,8,9]) [12,15,18] Main> hoge (T [1,2,3] [4,5,6] [7,8,9] [10,11,12]) [22,26,30]
ふむふむ,classとdataの使い分けは楽しそうだ.