haskell - 如何消除选择器功能的歧义?

标签 haskell ghc

在 GHC 8 中:

{-# LANGUAGE DuplicateRecordFields #-}

data Dog = Dog { name::String }
data Human = Human { name::String }

dog = Dog "Spike"


main = putStrLn $ name dog

此代码无法编译:
Ambiguous occurrence `name'
It could refer to either the field `name', defined at A.hs:4:22
                      or the field `name', defined at A.hs:3:18

如何正确检索我的狗的名字?

最佳答案

这应该工作:

main = putStrLn $ name (dog :: Dog)

DuplicateRecordFields详情:

Bare uses of the field refer only to the selector function, and work only if this is unambiguous.





However, we do not infer the type of the argument to determine the datatype, or have any way of deferring the choice to the constraint solver.



那里的例子和你的很像:

bad (p :: Person) = personId p



当有另一条记录为 personId 时,这将不起作用范围内的字段 - 即使看起来很明显:(

关于haskell - 如何消除选择器功能的歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37395098/

相关文章:

performance - GHC 产生冗余核心操作

Haskell:显示时抑制字符串周围的引号

haskell - 代数数据类型的计数

haskell - tinfo6 代表什么?

haskell - 使用通用元组函数一次多次折叠

haskell - ghc-pkg 和 cabal 是什么关系?

Haskell/GHC - Haskell 有没有办法只返回 16 位小数?

haskell - 如何在 Haskell 中将守卫与模式匹配结合起来? (我可以吗?)

haskell - 我应该使用什么结构来表达棋盘游戏中的回合?

haskell - Haskell 梁的简单 where 子句的类型错误