Haskell その4

少し馴染んできた(ウソ)ので、基本に戻って写経プログラミング。
http://www.hyuki.com/haskell/200412
結城氏の足跡をなぞる。ありがたや、ナムナム。
つまづいたとこだけ復習。

関数合成

test15 = head (tail [1,2,3,4,5])
test16 = (head . tail) [1,2,3,4,5]

これ↓もアリ。$は遅延適用演算子という。なんとなくカコイイ。

myTest = head $ tail [1,2,3,4,5]

全て結果は2

条件

f_isZero0 x =
    if x == 0
        then True
        else False
f_isZero1 x =
    if x /= 0
        then False
        else True
f_isZero2 x =
    case x of
        0 -> True
        _ -> False
f_isZero3 0 = True
f_isZero3 _ = False
f_isZero4 x = case x of { 0 -> True; _ -> False }

ガードで定義を選択させる↓のもアリ。

my_isZero x
    | x == 0 = True
    | otherwise = False

個人的にはパターンマッチングのやり方が好きになってきた。
”関数定義・オーバーロード”とあるが↓、型は同じだよなぁ。
http://www.nslabs.jp/haskell.rhtml

let式

f_distance2 x1 y1 x2 y2 =
    let xdiff = x2 - x1
        ydiff = y2 - y1
    in  sqrt(xdiff^2 + ydiff^2)

相変わらず↓の説明は僕の脳に合わないw
http://www.sampou.org/haskell/tutorial-j/patterns.html


whereもアリ。

my_distance x1 y1 x2 y2 =
    sqrt(xdiff^2 + ydiff^2)
        where
            xdiff = x2 - x1
            ydiff = y2 - y1

ラムダ計算

f_filter1 pred list =
    if null list
        then []
        else if pred (head list)
            then (head list) : f_filter1 pred (tail list)
            else f_filter1 pred (tail list)

f_positive n =
    if n > 0
        then True
        else False

 - f_filter1 f_positive [0,1,-1,2,-2,3,-3]      - [1,2,3]
(head list) : f_filter1 pred (tail list)

が一瞬何のことか分からなかった。リストの連結ね。


ふぅ。LLDNではレベル付けしてたそうで。
http://www.edit.ne.jp/~koic/?date=20050827

Haskellプログラマのレベル10
レベル0...Haskellを知っている
レベル1...『A Gentle Introduction to Haskell 98』を読んだが、ちっともやさしくないと思う

おお、レベル1にはなったのかw
あ、ウソ。
僕が読んだのは「やさしい Haskell 入門 (バージョン98)」ですからレベル0〜、残念〜!(もう古いね)。