haskell - 如何在 Haskell 中比较非 'Eq' 类型?

标签 haskell functional-programming

加载以下模块时出现错误:

No instance for (Eq Planet) arising from a use of ‘==’ • In the expression: planet == Mercury In a stmt of a pattern guard for an equation for ‘ageOn’:

如何检查行星是否等于某个行星?

module SpaceAge (Planet(..), ageOn) where

data Planet = Mercury
        | Venus
        | Earth
        | Mars
        | Jupiter
        | Saturn
        | Uranus
        | Neptune

mercury :: Float
mercury = 0.2408467

venus :: Float
venus = 0.61519726

earth :: Float
earth = 1.0

mars :: Float
mars = 1.8808158

jupiter :: Float
jupiter = 11.862615

saturn :: Float
saturn = 29.447498

uranus :: Float
uranus = 84.016846

neptune :: Float
neptune = 164.79132

ageOn :: Planet -> Float -> Float
ageOn planet seconds
   | planet == Mercury = seconds * mercury
   | planet == Venus = seconds * venus
   | planet == Earth = seconds * earth
   | planet == Mars = seconds * mars
   | planet == Jupiter = seconds * jupiter
   | planet == Saturn = seconds * saturn
   | planet == Uranus = seconds * uranus
   | planet == Neptune = seconds * neptune

最佳答案

您可以使用模式匹配:

ageOn :: Planet -> Float -> Float
ageOn <b>Mercury</b> seconds = seconds * mercury
ageOn <b>Venus</b> seconds = seconds * venus
ageOn <b>Earth</b> seconds = seconds * earth
ageOn <b>Mars</b> seconds = seconds * mars
ageOn <b>Jupiter</b> seconds = seconds * jupiter
ageOn <b>Saturn</b> seconds = seconds * saturn
ageOn <b>Uranus</b> seconds = seconds * uranus
ageOn <b>Neptune</b> seconds = seconds * neptune

但您也可以使 Planet 成为 Eq 类型类的实例。如果你只是想检查两个 Planet 是否相同,如果你使用相同的数据构造函数,你可以让 Haskell 使用 deriving 子句来实现它:

data Planet
  = Mercury
  | Venus
  | Earth
  | Mars
  | Jupiter
  | Saturn
  | Uranus
  | Neptune
  <b>deriving Eq</b>

关于haskell - 如何在 Haskell 中比较非 'Eq' 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66629663/

相关文章:

python - 将函数转换为单行列表理解时出现问题

java - Java 8 中 Collection<BiConsumer<A,B>> 的功能应用

haskell - 如何设置WinGHCi的工作目录

haskell - 在 Gloss 中设置 OpenGL 窗口提示

list - Haskell中的嵌套 block ?

algorithm - 如何对 n 元 Haskell 树的元素求和?

c++ - 将自定义仿函数与 std::generate_n() 算法一起使用的正确方法?

scala - Scala 中动态深度的 For 理解

function - 如何从类型签名实现功能?

haskell - 防止Haskell的类型变量增殖