在Haskell数据构造函数中输入检查 [英] Input checks in Haskell data constructors

查看:119
本文介绍了在Haskell数据构造函数中输入检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将输入检查添加到Haskell数据构造函数中?假设我有

How can I add input checks to Haskell data constructors? Let's say I have

import Data.Time.Calendar

data SchedulePeriod = SchedulePeriod { startDate :: Day
    , endDate :: Day
    , accrualStart :: Day
    , accrualEnd :: Day
    , resetDate :: Day
    , paymentDate :: Day
    , fraction :: Double }
    deriving (Show)

我想施加一个约束 startDate<结束日期。有没有办法做到这一点,而不创建一个抽象的数据类型?

and I want to impose a constraint startDate < endDate. Is there a way to do it without creating an abstract data type?

推荐答案

标准的方法是使用智能构造函数,它在创建值之前检查前提条件,并且不导出它使用的实际构造函数。正如你所说的那样,这是创建一个抽象数据类型。

The standard way is to use a smart constructor that checks the precondition before creating the value, and to not export the real constructor it uses. Of course, this is creating an abstract data type, as you said.

没有智能构造函数的唯一方法就是 邪恶的类型系统hackery(你不能使用标准的 Day 类型)。

The only way to achieve this without a smart constructor would be really evil type-system hackery (and you wouldn't be able to use the standard Day type).

这篇关于在Haskell数据构造函数中输入检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆