我想在第二個引數中撰寫一個固定型別的多型函式(例如 mod),回傳值的型別由第一個引數決定。這是我的實作:
f :: Integral a => a -> Int -> a
f n m = mod n m
它得到了錯誤:
Couldn't match expected type ‘a’ with actual type ‘Int’
‘a’ is a rigid type variable bound by
the type signature for:
f :: forall a. Integral a => a -> Int -> a
如果我不想用第一個引數的特定型別(f1 :: Int -> Int -> Int 和 f2 :: Integer -> Int -> Integer)撰寫兩個函式,是否有更優雅的實作?
uj5u.com熱心網友回復:
mod要求其兩個引數的型別相同。因此,用于從 anfromIntegral轉換為 type :mInta
f :: Integral a => a -> Int -> a
f n m = mod n (fromIntegral m)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363866.html
