多変量関数の例を探しているときに、次のリソースを見つけました: StackOverflow: How to create a polyvariadic haskell function? 、そして次のような回答スニペットがありました:
class SumRes r where
sumOf :: Integer -> r
instance SumRes Integer where
sumOf = id
instance (Integral a, SumRes r) => SumRes (a -> r) where
sumOf x = sumOf . (x +) . toInteger
次に、次を使用できます。
*Main> sumOf 1 :: Integer
1
*Main> sumOf 1 4 7 10 :: Integer
22
*Main> sumOf 1 4 7 10 0 0 :: Integer
22
*Main> sumOf 1 4 7 10 2 5 8 22 :: Integer
59
一見したところかなりトリッキーだとわかったので、好奇心のために少し変更してみましたが、次のようになりました。
class SumRes r where
sumOf :: Int -> r
instance SumRes Int where
sumOf = id
instance (SumRes r) => SumRes (Int -> r) where
sumOf x = sumOf . (x +)
に変更Integer
しInt
、instance (Integral a, SumRes r) => SumRes (a -> r) where
多態性を減らしましたinstance (SumRes r) => SumRes (Int -> r) where
それをコンパイルするには、XFlexibleInstances
フラグを設定する必要がありました。関数をテストしようとするsumOf
と、問題が発生しました。
*Main> sumOf 1 :: Int
1
*Main> sumOf 1 1 :: Int
<interactive>:9:9
No instance for (Num a0) arising from the literal `1'
The type variable `a0' is ambiguous...
それから私は試しました:
*Main> sumOf (1 :: Int) (1 :: Int) :: Int
2
型クラス内でInt
を使用しているのに、なぜ Haskell はこの状況で が必要であると推測できないのでしょうか?Int
SumRes