Open maeken2010 opened 9 years ago
書きながら思ったのですが除算の小数部分自体はRatio用いる方法がありますね.このままでは整数値同士しかできませんが…
import Data.Ratio
syous n m = fromRational $ (n`mod`m) % m
まず2 から答えます。
- 数式
(a/b) - (fromIntegral (a
divb))
を関数定義した時と直接実行した時に何故型が変わるのか
についてですけれど、 ghci で定義している文だと関数じゃなくて定数だからです。
syouss は関数なので、
ghci> (a/b) - (fromIntegral (a
divb))
ではなくて
ghci> \a b -> (a/b) - (fromIntegral (a
divb))
です。
そうすると
Prelude> :t \a b -> (a/b) - (fromIntegral (a`div`b))
\a b -> (a/b) - (fromIntegral (a`div`b))
:: (Integral a, Fractional a) => a -> a -> a
で
*Main> :t syouss
syouss :: (Integral a, Fractional a) => a -> a -> a
と同じです。
そして、 Int の値が実行できない問題はこっちでも発生します。
*Main> (\a b -> (a/b) - (fromIntegral (a`div`b))) (10 :: Int) (3 :: Int)
<interactive>:17:12:
No instance for (Fractional Int) arising from a use of ‘/’
In the first argument of ‘(-)’, namely ‘(a / b)’
In the expression: (a / b) - (fromIntegral (a `div` b))
In the expression: \ a b -> (a / b) - (fromIntegral (a `div` b))
これはどうしてかと言えば Int だと Fractional に明示的に変換しないといけないからです。
Num, Fractional, Integral の関係は https://www.haskell.org/onlinereport/basic.html とかになってます。
Integral である Integer にすると、 Fractional の型クラスを持ってないからエラーになるわけです。
ん? ごめんちょっと問題を勘違いしてたかも。 上の全然関係無いこと言ってる説が。ちょっと待って
除算の小数部分を求めたくて以下の関数syoussと定数n,mを用意したのですが,
ghciで:loadで読み込んで実行しようとするとエラーに
nとmの型を調べるとなぜかIntegerでした. ghciで
let a = 10
のようにすると型はa :: Num a => aとなりましたがsyoussはまだ実行できませんでした.試しにghciで
(a/b) - (fromIntegral (a
divb))
を直接実行すると計算できました.型を見てみましたがなぜか異なっていました
長くなってしまいまいましたが,以上より2つの疑問点があります.
(a/b) - (fromIntegral (a
divb))
を関数定義した時と直接実行した時に何故型が変わるのか