IT練習ノート

IT関連で調べたこと(実際は嵌ったこと)を書いています。

Haskellの2種類の割り算

-- 割り算結果は小数部分込み
Prelude> 7 / 2
3.5
Prelude> :t 7 / 2
7 / 2 :: Fractional a => a

--割り算結果は整数扱い
Prelude> 7 `div` 2
3
Prelude> :t 7 `div` 2
7 `div` 2 :: Integral a => a

-- drop の第一引数の型は int のため下記はエラーとなる
Prelude> drop (7 / 2) "abcdefg"

<interactive>:17:9:
    No instance for (Fractional Int) arising from a use of `/'
    Possible fix: add an instance declaration for (Fractional Int)
    In the first argument of `drop', namely `(7 / 2)'
    In the expression: drop (7 / 2) "abcdefg"
    In an equation for `it': it = drop (7 / 2) "abcdefg"

-- こちらは正常終了
Prelude> drop (7 `div` 2) "abcdefg"
"defg"

-- それぞれの型を確認すると
Prelude> :t (/)
(/) :: Fractional a => a -> a -> a
Prelude> :t div
div :: Integral a => a -> a -> a
Prelude> 

http://stackoverflow.com/questions/7368926/division-in-haskell