Saturday 10 August 2013

Haskell 入門! (10)

とうとう2桁行ったけど予約投稿やから特に感慨もない.
読みづらいかもしれない文章でごめんなさいね.

今回は前回作った  list とかから要素を取り出したい,が,まだそれほど上手くいかない.


Retrieving Values

list とか tuple 作ったんだからそこから要素引き出したいぜ!
っていう話なんやけど,ちょっと準備の必要な話でもあるので,まずは単純なやつだけ.
ちゃんと将来的には大丈夫になる(らしい)ので我慢だ!
いずれにしても割と気持ち悪いぜ!
  • list. head がリストの頭を,tail がそれ以降の部分を返す.正確にいうならそういう写像.
    これ,(:) で繋いだのの端っこを切ることでできている.
    Prelude> head [2,5,3,6]
    2
    Prelude> tail [2,5,3,6]
    [5,3,6]
    Prelude> head (2:5:3:6:[])
    2
    Prelude> head "there"
    't'
    Prelude> tail "there"
    "here"
    Prelude> tail "t"
    ""
    Prelude> tail [1]
    []
    Prelude> tail []
    *** Exception: Prelude.tail: empty list
    Prelude> head []
    *** Exception: Prelude.head: empty list
    
    tail [1][] になるのは [1]1:[] だから,かな.
  • pair (要素2つの tuple) : fst で 1つめの要素を,snd で 2つめの要素を取得.
    Prelude> fst (2,5)
    2
    Prelude> fst (True,"noo")
    True
    Prelude> fst( snd ( (True, 3), (2,"there")))
    2
    Prelude> fst (2,3,1)
    
    <interactive>:5:5:
        Couldn't match expected type `(a0, b0)'
                    with actual type `(t0, t1, t2)'
        In the first argument of `fst', namely `(2, 3, 1)'
        In the expression: fst (2, 3, 1)
        In an equation for `it': it = fst (2, 3, 1)
    
    pair にしかこれは使えないんだ,すまない.((2,3)(2,3,4) では type が違うからね)

練習問題.
  1. ( ("Hello", 4), True) から 4 を取り出してみよう.
  2. tuple で list の 頭と残りを返す関数書いてみよう.
  3. headtail で list の 5番目の要素を返す関数を書いてみよう.どこかどう面倒くさいか考えておこう.

No comments:

Post a Comment