首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何比较Haskell中的非Eq类型?

如何比较Haskell中的非Eq类型?
EN

Stack Overflow用户
提问于 2021-03-14 21:18:56
回答 1查看 135关注 0票数 2

当加载以下模块时,我会得到错误:

没有(Eq行星)的例子,因为在表达式中使用了‘==’·:==行星水星在一个模式保护器中,用于“ageOn”的一个方程:

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

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2021-03-14 22:34:57

代码语言:javascript
复制
ageOn planet seconds = seconds * case planet of
  Mercury -> mercury
  Venus -> venus
  Earth -> earth
  Mars -> mars
  ...

或者更好的是,考虑到向上的因素。

代码语言:javascript
复制
yearLength :: Planet -> Float
yearLength = \case
  Mercury -> mercury
  Venus -> venus
  ...

ageOn planet seconds = yearLength planet * seconds

同时,我认为你的逻辑可能有错误。如果我活了一个地球年,我就活了超过一个水星年。因此,根据您的函数的确切含义,您可能需要定义

代码语言:javascript
复制
ageOn planet earthYears = earthYears / yearLength planet
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66629663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档