【问题标题】:Checking function in HaskellHaskell 中的检查函数
【发布时间】:2015-09-17 02:00:46
【问题描述】:

我正在做一些 CS 作业,这是我第一次使用 Haskell,所以我有一个问题。

我已经声明了一个数据类型

data Date = Date Int Int Int deriving (Show)

我有这个函数 testdate:

testdate :: Date -> Maybe Date
testdate (Date m d y) = if 1 <= m && m <= 12 && 1 <= d && d <= 31 && y >= 0
    then
        True
    else
        False

我想创建一个新函数来检查 testdate 是真还是假,然后将日期返回给您。 类似:

betterdate :: Date -> Maybe Date
betterdate (Date m d y) if (testdate = True) //I know this part doesn't work
     then Just (Date m d y) 
     else Nothing

我该怎么做?

【问题讨论】:

  • 你不需要testdate的定义中的if ... then True else False1 &lt;= m &amp;&amp; ... &amp;&amp; y &gt;= 0 表达式本身的计算结果为 TrueFalse,因此您的函数就是这样。
  • 另外,当你比较两个东西时,你使用相等运算符 == 而不是 =。您还将一个函数与一个 Bool 进行比较,这没有意义(例如,它不进行类型检查)。你可能打算这样做testdate (Date m d y) == True
  • 函数testDate的类型错误:它声称返回Maybe Date,但实际上返回Bool。你需要给它正确的类型(或者完全省略类型让haskell为你推断它)才能使用它。

标签: haskell


【解决方案1】:

您想将日期传递给testdate 函数。这应该有效:

betterdate d = if testdate d
    then Just d
    else Nothing

如果你真的想解压参数列表中的Date,那么你可以这样做以避免在任何地方重复(Date m d y)

betterdate date@(Date m d y) = if testdate date
    then Just date
    else Nothing

【讨论】:

  • 非常感谢!没想到会这么简单。感谢帮助
  • 高级版本:betterdate = mfilter testdate . Just。 (mfilterControl.Monad 中。)
猜你喜欢
  • 2017-12-04
  • 1970-01-01
  • 2015-12-16
  • 2013-11-21
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 2022-03-06
  • 2012-04-15
相关资源
最近更新 更多