第2回 スタートHaskell 感想
今回は参加者が 100 名以上いた前回までとは違い、50名強の参加者だった。人が少ないなと思ったが、勉強会としては多い方だろうな。
第 1 部
予習してきた部分の発表。発表だけかと思いきや熱い議論が始まる展開に。初心者向けの勉強会と銘打たれているが、Haskellに詳しい方も参加されているので、いろいろとためになる話が聞けてよかった。
第 2 部
演習。本当に初心者向け?皆さん解くのが速い。
elem は中置記法
Haskeller は
elem 'c' "abcdefg"
よりも
'c' `elem` "abcdefg"
と書く人が多いらしい。英語のように読むことができるので。elem に限った話ではないけど。
-Wall -O
ghc(i) の実行時には -Wall と -O のオプションを付けるべし。-Wall は警告をすべて表示させる。-O は最適化を行う。gcc のオプションと同じ。
ただ問題が。-Wall を付けることで実行時に警告が出力される場合がある。コンパイル時には警告は出ない。これはちょっと使いづらい。
% ghci -O -Wall section7_13.hs GHCi, version 7.0.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Loading package ffi-1.0 ... linking ... done. [1 of 1] Compiling Main ( section7_13.hs, interpreted ) Ok, modules loaded: Main. *Main> nmerge [[9],[2,5,7],[1,4],[],[3,6],[8]] <interactive>:1:37: Warning: Defaulting the following constraint(s) to type `Integer' (Num a0) arising from the literal `8' at <interactive>:1:37 (Ord a0) arising from a use of `nmerge' at <interactive>:1:1-6 In the expression: 8 In the expression: [8] In the first argument of `nmerge', namely `[[9], [2, 5, 7], [1, 4], [], ....]' <interactive>:1:37: Warning: Defaulting the following constraint(s) to type `Integer' (Num a0) arising from the literal `8' at <interactive>:1:37 (Ord a0) arising from a use of `nmerge' at <interactive>:1:1-6 (Show a0) arising from a use of `print' at <interactive>:1:1-39 In the expression: 8 In the expression: [8] In the first argument of `nmerge', namely `[[9], [2, 5, 7], [1, 4], [], ....]' [1,2,3,4,5,6,7,8,9]
書き方が悪いのかと思ったが http://haskell.org/ghc/docs/7.0.3/html/users_guide/options-sanity.html を見ると、-fwarn-type-defaults が原因のようだ。なので -fwarn-type-defaults をなくしてみる。オプションは -fno-warn-... とすることで off にすることができる。
% ghci -O -Wall -fno-warn-type-defaults section7_13.hs GHCi, version 7.0.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Loading package ffi-1.0 ... linking ... done. [1 of 1] Compiling Main ( section7_13.hs, interpreted ) Ok, modules loaded: Main. *Main> nmerge [[9],[2,5,7],[1,4],[],[3,6],[8]] [1,2,3,4,5,6,7,8,9]
消えた。毎回打つのは面倒なので ~/.ghci にオプションを追加。
~/.ghci
:set -O :set -Wall :set -fno-warn-type-defaults
数
Haskell のコードを書いていてよくハマるのが数値の型変換のところ。fromRational, toRational って何ですか。
*Main> :t fromRational fromRational :: Fractional a => Rational -> a *Main> :t toRational toRational :: Real a => a -> Rational
英語が不得意な自分のために書いておくと
Rational -- 有理数 Real -- 実数 Fractional -- 分数
有理数と分数の違いが...。
クラスの階層関係は http://www.sampou.org/haskell/report-revised-j/basic.html#standard-classes で。数関連のクラスは複雑。