【问题标题】:Does PureScript support “format strings” like C / Java etc.?PureScript 是否支持 C/Java 等“格式字符串”?
【发布时间】:2016-03-04 16:53:13
【问题描述】:

我需要输出一个前导零和六位数的数字。在 C 或 Java 中,我会使用 "%06d" 作为格式字符串来执行此操作。 PureScript 是否支持格式字符串?或者我将如何实现这一目标?

【问题讨论】:

    标签: purescript


    【解决方案1】:

    我不知道有任何模块可以支持 PureScript 中的 printf 样式功能。如果有一种类型安全的方式来格式化数字,那就太好了。

    与此同时,我会写这样的东西:

    import Data.String (length, fromCharArray)
    import Data.Array (replicate)
    
    -- | Pad a string with the given character up to a maximum length.
    padLeft :: Char -> Int -> String -> String
    padLeft c len str = prefix <> str
      where prefix = fromCharArray (replicate (len - length str) c)
    
    -- | Pad a number with leading zeros up to the given length.
    padZeros :: Int -> Int -> String
    padZeros len num | num >= 0  = padLeft '0' len (show num)
                     | otherwise = "-" <> padLeft '0' len (show (-num))
    

    这会产生以下结果:

    > padZeros 6 8
    "000008"
    
    > padZeros 6 678
    "000678"
    
    > padZeros 6 345678
    "345678"
    
    > padZeros 6 12345678
    "12345678"
    
    > padZeros 6 (-678)
    "-000678"
    

    编辑:同时,我编写了一个可以用这种方式格式化数字的小模块: https://github.com/sharkdp/purescript-format

    对于您的特定示例,您需要执行以下操作:

    如果你想格式化Integers:

    > format (width 6 <> zeroFill) 123
    "000123"
    

    如果你想格式化数字s

    > format (width 6 <> zeroFill <> precision 1) 12.345
    "0012.3"
    

    【讨论】:

    • 我实际上已经开始开发一个库来支持这一点:github.com/sharkdp/purescript-format
    • 酷,我会仔细看看你在用 Monoid 和 Semigroup 做什么。顺便说一句,您上面的解决方案比我昨天自己编写的解决方案更通用?我仍在尝试掌握 PureScript 的窍门(严格,没有 (:) 用于递归中的数组解构,数据类型 Tuple 而不是(,),还有更多内容)。
    • 我已经发布了 purescript-format 的第一个版本。我已经相应地更新了我的答案。属性的 Semigroup/Monoid 实例仅用于以简单的方式组合它们。
    • 是的,我看到了,通过定义 append 并提供“空”默认值。 Sieht gut aus ?
    猜你喜欢
    • 1970-01-01
    • 2018-03-25
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2021-12-17
    • 2013-03-04
    • 2012-09-01
    相关资源
    最近更新 更多