自定义printf无法打印任何内容

时间:2019-12-25 23:41:51

标签: haskell printf

我为PrintArg实现了自定义Maybe实例:

import Text.Printf

instance PrintfArg a => PrintfArg (Maybe a) where
    formatArg Nothing f str = formatArg "Nothing" f str
    formatArg (Just x) f@(FieldFormat Nothing _ _ _ _ _ _) str = "Just " ++ formatArg x f str
    formatArg (Just x) f@(FieldFormat (Just w) _ Nothing _ _ _ _) str = let
        str' = formatArg x (f {fmtWidth = Nothing}) ""
        in replicate (max 0 (w - 5 - length str')) ' ' ++ "Just " ++ str' ++ str
    formatArg (Just x) f@(FieldFormat (Just w) _ (Just _) _ _ _ _) str = "Just " ++ formatArg x (f {fmtWidth = Just (w-5)}) str

它可以很好地打印Just值:

*Main> printf "%10d\n" (Just 2)
    Just 2
*Main> printf "%-10d\n" (Just 2)
Just 2    
*Main> printf "%+10d\n" (Just 2)
   Just +2
*Main> printf "% 10d\n" (Just 2)
   Just  2
*Main> printf "%010d\n" (Just 2)
Just 00002

但是由于类型不明确,它无法打印Nothing

*Main> printf "%v\n" Nothing

<interactive>:24:1: error:
    • Could not deduce (PrintfArg a0) arising from a use of ‘printf’
      from the context: PrintfType t
        bound by the inferred type of it :: PrintfType t => t
        at <interactive>:24:1-21
      The type variable ‘a0’ is ambiguous
      These potential instances exist:
        instance [safe] PrintfArg Integer -- Defined in ‘Text.Printf’
        instance [safe] PrintfArg a => PrintfArg (Maybe a)
          -- Defined at Test.hs:3:10
        instance [safe] PrintfArg Char -- Defined in ‘Text.Printf’
        ...plus five others
        ...plus 9 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the expression: printf "%v\n" Nothing
      In an equation for ‘it’: it = printf "%v\n" Nothing

是否有解决方法?

0 个答案:

没有答案