具有不同字段名称的记录的 haskell 变体
鉴于此:
data Foo = Bar { name :: String } | Baz { nickname :: String }
函数 name
和 nickname
似乎都是 Foo ->; 类型。 String
:
:t name
name :: Foo -> String
:t nickname
nickname :: Foo -> String
但是,定义不完整,因为以下两个表达式都会引发模式匹配错误:
name $ Baz { nickname = "Bob" }
nickname $ Bar { name = "Fred" }
是否可以完成 name
和 nickname
的定义,即类似:
name Baz { nickname = n } = ...
nickname Bar { name = n } = ...
在拥抱中尝试此操作会产生诸如“变量名的多个声明”之类的错误。
Given this:
data Foo = Bar { name :: String } | Baz { nickname :: String }
Both the functions name
and nickname
seem to be of type Foo -> String
:
:t name
name :: Foo -> String
:t nickname
nickname :: Foo -> String
However, the definitions are incomplete since both of the following expressions will raise pattern match errors:
name $ Baz { nickname = "Bob" }
nickname $ Bar { name = "Fred" }
Is it possible to complete the definitions of name
and nickname
, i.e. something like:
name Baz { nickname = n } = ...
nickname Bar { name = n } = ...
Trying this in hugs yields errors like "Multiple declarations for variable name".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这是不可能的。字段名称是就范围而言的顶级函数,因此不能重新定义或扩展。让它们成为全部功能就像让
head
成为一个功能一样不可能。No, it's not possible. The field names are top-level functions with respect to scope and thus cannot be redefined or extended. It's as impossible to make them total functions as it is to make
head
one.尝试 -XDataKinds< /a> 扩展名,它允许您将数据构造函数提升为种类。
请注意,您将需要 12 天前发布的 GHC 7.4.1。现在是问这个问题的好时机!
Try the -XDataKinds extension, it allows you to promote data constructors to be kinds.
Note that you'll need GHC 7.4.1, which was released just 12 days ago. This is a good time to be asking this question!