プログラミング勉強ログ

プログラミングの勉強記録

Yet Another Haskell 3章 (3.1)

3.3.1 Strings
文字列に関して

Haskellでは文字列はString型で表され、その実体は文字型Charのリストである。

Prelude> 'H':'e':'l':'l':'o':[]
"Hello"

 

リストは++オペレータを使って結合できる。

Prelude> [1,2] ++ [3,4,5]
[1,2,3,4,5]

 

文字列もリストなので、もちろん++が使える。

Prelude> "Hello " ++ "World"
"Hello World"

 

show関数を使って、文字列でない値を文字列に変換できる。

Prelude> show 1
"1"
Prelude> show (1,2)
"(1,2)"
Prelude> show [1,2,3]
"[1,2,3]"
Prelude> show "1"
"\"1\""

最後の結果は意外。

 

Prelude> show (show "1")
"\"\\\"1\\\"\""

文字列に対してshowを適用すると、元の文字列の両端に"を付けて、さらにそれをエスケープするのかな?

 

Prelude> show show

<interactive>:50:1:
No instance for (Show (a0 -> String))
arising from a use of `show'
Possible fix: add an instance declaration for (Show (a0 -> String))
In the expression: show show
In an equation for `it': it = show show

関数はshowできないと。

 

read関数を使って文字列を文字列でない値に変換できる。

Prelude> read "5" + 3
8

 

なお、

Prelude> read "5"

とすると下のエラーがでる。

<interactive>:58:1:
Ambiguous type variable `a0' in the constraint:
(Read a0) arising from a use of `read'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: read "5"
In an equation for `it': it = read "5"

 

おそらく、read "5" + 3では、 + 3からreadが返すべき型(この場合はNumber?)が推論できるのだけど、read "5"だけだと、型の推論ができないから駄目なんだろう。