プログラミング勉強ログ

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

Yet Another Haskell 4章 (1)

4.1 Simple Types

Haskellは静的型付け言語であり、全ての式は型を持っている。
さらに、タイプインターフェイスというシステムがあり、式の型を指定する必要がない。型はコンテキストから推論される。


HugsGHCでは、:tコマンドを使用することで式の型を調べることができる。

Prelude> :t 'c'
'c' :: Char

式'c'の型はCharだ。


Int(整数型), Double(浮動小数点型), Char(文字型), String(文字列型)等など、たくさんの組み込み型がある。

文字列の型は、

Prelude> :t "Hello"
"Hello" :: [Char]

原文だと、Stringになっているけど、まあ同じものだし。


比較の結果はBool

Prelude> :t 'a' == 'b'
'a' == 'b' :: Bool


違う型同士を比較しようとすると、エラーになる。

Prelude> :t 'a' == "b"

<interactive>:1:8:
    Couldn't match expected type `Char' with actual type `[Char]'
    In the second argument of `(==)', namely `"b"'
    In the expression: 'a' == "b"


::を使って明示的に型を指定することもできる。

Prelude> :t "b"::String
"b"::String :: String


上の例では"a"の型はStringの可能性しかないため特に意味は無いが、数値の場合は少し状況が異なる。

Prelude> :t 5::Int
5::Int :: Int
Prelude> :t 5::Double
5::Double :: Double

5はIntともDoubleとも解釈できる。

もし、型を指定しなければどうなるか?

Prelude> :t 5
5 :: Num a => a

変な結果になった。


5の型aはNumクラスのインスタンスという意味らしい。
詳しくは4.3で扱う。

Exercise 4.1

1. 'h':'e':'l':'l':'o':[] :: [Char]
2. [5, 'a'] -> error
3. (5,'a') :: Num t => (t, Char)
4. (5::nt) + 10 :: Int
5. (5::Int) + (10::Double) -> error