为访问者记录语法默认值 [英] Record syntax default value for accessor

查看:135
本文介绍了为访问者记录语法默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我刚刚撰写答案时,我遇到了一个有趣的问题:

  data Gender = Male |女性
派生(方程式,显示)

数据年龄=婴儿|孩子| PreTeen |成人
派生(Eq,Show,Ord)

data衣物=裤子性别年龄
|衬衫性别年龄
|裙子年龄 - 假定为女性
派生(显示,公式)

假设我希望使用记录语法编写最终数据类型:

  data衣服=裤子{gender :: Gender,age :: Age} 
|衬衫{性别::性别,年龄::年龄}
|裙子{age :: Age}
导出(Show,Eq)

问题是,我希望 gender $ skirt foo 始终评估为(不管 foo ,这是一个年龄)。我可以想到几种方法来实现这一点,但他们要求我使用智能构造函数,理论上允许


  1. >裙子男foo 但不暴露构造函数

  2. 定义我自己的性别函数

使用#1,通过不暴露模块中的构造函数,我可以有效地防止模块的用户利用记录语法。对于#2,我必须完全放弃记录语法,或者定义一个额外的函数 gender',这又会破坏记录语法。



有没有办法既利用记录语法,又为我的构造函数提供了一个默认,不可更改的值?我也接受非记录语法解决方案(镜头,也许是?),只要它们一样优雅(或更多)。

解决方案


是否有一种方法既可以利用记录语法,也可以为我的一个构造函数提供默认,不可更改的值?

如果没有令人信服的反例,答案似乎是否。


As I was writing up an answer just now, I ran across an interesting problem:

data Gender = Male | Female
            deriving (Eq, Show)

data Age = Baby | Child | PreTeen | Adult
         deriving (Eq, Show, Ord)

data Clothing = Pants Gender Age
              | Shirt Gender Age
              | Skirt Age         -- assumed to be Female
              deriving (Show, Eq)

Suppose I wish to write the final data type with record syntax:

data Clothing = Pants {gender :: Gender, age :: Age}
              | Shirt {gender :: Gender, age :: Age}
              | Skirt {age :: Age}
              deriving (Show, Eq)

The problem is, I want gender $ Skirt foo to always evaluate to Female (regardless of foo, which is an Age). I can think of a few ways to accomplish this, but they require that I either

  1. use smart constructors, theoretically allowing Skirt Male foo but not exposing Constructors
  2. define my own gender function

With #1, by not exposing the constructor in the module, I effectively prevent users of the module from taking advantage of record syntax. With #2, I have to forego record syntax entirely, or define an additional function gender', which again defeats record syntax.

Is there a way to both take advantage of record syntax, and also provide a "default", unchangeable value for one of my constructors? I am open to non-record-syntax solutions as well (lenses, perhaps?) as long as they are just as elegant (or moreso).

解决方案

Is there a way to both take advantage of record syntax, and also provide a "default", unchangeable value for one of my constructors?

In the absence of a convincing counterexample, the answer seems to be "no".

这篇关于为访问者记录语法默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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