我可以在IO monad中使用printf吗?

时间:2012-07-23 02:45:59

标签: haskell

stopLoss函数导致以下错误:

Could not deduce (Text.Printf.PrintfType (m a0))
arising from the ambiguity check for `stopLoss'
from the context (Monad m,
                Text.Printf.PrintfType (m b),
                Text.Printf.PrintfType (m a))
bound by the inferred type for `stopLoss':
  (Monad m, Text.Printf.PrintfType (m b), 
   Text.Printf.PrintfType (m a)) =>
   Float -> Float -> Float -> m b
Possible fix:
   add an instance declaration for (Text.Printf.PrintfType (m a0))

When checking that `stopLoss'
has the inferred type `forall (m :: * -> *) a b.
  (Monad m, Text.Printf.PrintfType (m b),
   Text.Printf.PrintfType (m a)) =>
   Float -> Float -> Float -> m b'
Probable cause: the inferred type is ambiguous

功能:

stopLoss qty pb lossRate = do
    let t = qty * pb * (1 + sxf)
    printf "Stop Loss at: %.2f\n" ((pb - (t * lossRate) / qty) :: Float)
    printf "Lost Money: %.2f\n"  ((t * lossRate) :: Float)

任何建议都表示赞赏!

1 个答案:

答案 0 :(得分:5)

printf的类型为PrintfType r => String -> rPrintfType的以下实例可用:

IsChar c => PrintfType [c]   
PrintfType (IO a)    
(PrintfArg a, PrintfType r) => PrintfType (a -> r)

(最后一个只是让printf表现得像是多变量的。)

这里stopLoss是一个多态函数;类型IO ()无法自动推断,GHC假设该函数适用于任何monad。因此,GHC抱怨通用monad的PrintfType实例不存在。

提供类似Float -> Float -> Float -> IO ()的类型签名应该会有所帮助。