haskell - 显示前面带有“+”号的数字
问题描述
我是函数式编程和 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 知识。
解决方案
您应该解压缩数据构造函数,从而获取参数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
推荐阅读
- graphql - SuiteCRM 与 Graphql 的集成
- swift - Parsing Infix Mathematical Expressions in Swift Using Regular Expressions
- jquery - $(...).insertFusionCharts 不是使用 jQuery 的角度函数
- scala - scala中数组项的索引
- java - Switch 语句不允许我将 ArrayLists 的最后一个元素添加到新的 ArrayList
- selenium - 从动态 Web 表中获取基于列和行名称的特定值,其中列和行的位置也是动态的
- c# - 如何使用代码优先方法进行长文本
- arrays - 数据类对象或数组
- powershell - 如何显示几个 mp4 文件的持续时间
- firebase - Firestore 合并不返回 Pormise