Friday 9 August 2013

Haskell 入門! (9)

重要なデータ構造, list と tuple について.
en.wikibooks の Haskell に基づいたものです. CC-BY-SA で配布.



Lists and tuples
list と tuple のお話.

Lists

list の書き方:
numbers = [1,2,3,86]
strings = ["here", "are", "some", "strings"]
bools = [True, False, True, False]
  • 同じ type のものだけを集められます(異なる type をまとめようとすると type error:
    Prelude> let thisdoesntwork = [2, 'a']
    
    <interactive>:5:23:
        No instance for (Num Char) arising from the literal `2'
        Possible fix: add an instance declaration for (Num Char)
        In the expression: 2
        In the expression: [2, 'a']
        In an equation for `thisdoesntwork': thisdoesntwork = [2, 'a']
    
  • (足すもの):(list)という記法で要素を足した list を手に入れることができます(このことを cons (verb) というらしい).この時の evaluation は右から左に行われ,好きなだけつなげて行けます.
    Prelude> let numbers = [1,2,3,1,4]
    Prelude> 1:numbers
    [1,1,2,3,1,4]
    Prelude> 1:0:4:numbers
    [1,0,4,1,2,3,1,4]
    Prelude> numbers:numbers
    
    <interactive>:5:9:
        Couldn't match type `Integer' with `[Integer]'
        Expected type: [[Integer]]
          Actual type: [Integer]
        In the second argument of `(:)', namely `numbers'
        In the expression: numbers : numbers
        In an equation for `it': it = numbers : numbers
    
    っていう感じ.
    • ほんま言うと [1,2,3] っていうの自体も 1:2:3:[] の syntax sugar. 最後の [] 忘れないように.
    • (:) も例によって関数.
      Prelude> :t (:)
      (:) :: a -> [a] -> [a]
      
    • 1:-2:4:[] とすると :- を関数かと思わはってエラーが出るので,スペースを入れましょう.類似のことはちょくちょくあるみたいなので気をつける.
    • 前言った通り String は Char の list なので,
      Prelude> 't':"here"
      "there"
      Prelude> "me" == ['m','e']
      True
      
  • あれ,それなら [] の type ってなんなんだろう.
    Prelude> :t []
    [] :: [a]
    
    Haskell 「なんかわからんけどなんかのリストや」
    なるほど.
  • 型さえ揃ってれば何でもいいので,(型が同じ) list の list も作れます.
    listOfLists = [ [1,2], [3,4], [5,6,7]]
    anotherList = []:[1]:[]:[]
    
    でもこんなのはだめよ
    lol  = [ 1, [1,2]]
    lol2 = [ ['a'], [2] ]
    

練習問題.はまあ省略でいいわ.

Tuples

Tuples の書き方:
tuple1 = (1,3.3)
tuple2 = (True, 3)
tuple3 = (4, 5, "Six", True, 'b')
tuple4 = ((2,3), [2,3])
Tuple は
  • 要素の数は変更できない (immutable). (:) で cons することも従ってできない.
    • だから座標を表すのとかにいいかも.
    • 要素の数 n に対して一般には n-tuple. 2 の時は pair, 3の時は triple ということが多い.一応それ以降は quadruples, quintuples と続く.tuple の名はここから.
  • 要素の型がそろってなくてもいい.
    • 電話帳とかにいいかも.

補足事項
  • 関数のとる値とかがこれになるようにしとくと複数の値を返す相当だぜ
  • マスターいつもの
    Prelude> :t ('a', True)
    ('a', True) :: (Char, Bool)
    Prelude> :t ()
    () :: ()
    
    前者からわかるとおり,('a', True)(True, 'a') は type が別になるので注意.

というわけで tuple と list をそれぞれ入れ子にしたりできる.
((2,3), True)
((2,3), [2,3])
[(1,2), (3,4), (5,6)]
たとえば
[(1,2),(3,4,5)]
は通りませんで.

No comments:

Post a Comment