首页 > 解决方案 > 显示前面带有“+”号的数字

问题描述

我是函数式编程和 Haskell 的新手,很难理解如何制作自己的数据类型。作为学习资源,我一直在使用http://learnyouahaskell.com/,但我仍然无法掌握一些想法。

我的具体问题是,我正在尝试为我的自定义数据类型创建一个显示实例,它总是在显示的任何内容前面显示“+”符号(在我的情况下,输入 555 将是“+555”)。这就是我一直在尝试解决的方法。

data CountryCode = CountryCode Integer deriving Eq

instance Show CountryCode where
    show _ = "+" : _

这就是我尝试加载它时得到的。

[1 of 1] Compiling Main             ( phonetest.hs, interpreted )

phonetest.hs:6:14: error:
    • Couldn't match type ‘[Char]’ with ‘Char’
      Expected type: String
        Actual type: [[Char]]
    • In the expression: "+" : _
      In an equation for ‘show’: show _ = "+" : _
      In the instance declaration for ‘Show CountryCode’

phonetest.hs:6:20: error:
    • Found hole: _ :: [[Char]]
    • In the second argument of ‘(:)’, namely ‘_’
      In the expression: "+" : _
      In an equation for ‘show’: show _ = "+" : _
    • Relevant bindings include
        show :: CountryCode -> String (bound at phonetest.hs:6:5)
Failed, modules loaded: none.

我可以从错误消息中得到一些东西,但不足以使其正常工作。我也尝试过show (CountryCode _) = "+" : _,但 haskell 仍然抱怨。对我来说,这似乎很合乎逻辑,但显然我缺乏一些基本的 haskell 知识。

标签: haskellfunctional-programming

解决方案


您应该解压缩数据构造函数,从而获取参数x。然后我们可以使用守卫来检查该值是正数还是负数。如果它是肯定的,我们可以'x'在结果之前添加show x

instance Show CountryCode where
    show (CountryCode x) | x >= 0 = '+' : show x
                         | otherwise = show x

或者我们可以像@chepner 建议的那样在积极和消极的情况下省略分支:

instance Show CountryCode where
    show (CountryCode x) = '+' : show x

推荐阅读