Record syntax default value for accessor

好久不见. 提交于 2019-12-01 03:51:59

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".

Yes there is a tension between types and data... which by the way shows how thin is the line.

The pratical answer is to use a default instance as indicated in the Haskell Wiki. It does answer your exact question since you must give up direct constructor use.

Thus for your example,

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

skirt = Skirt { gender=Female, age=NoAge }

then developpers can create new instances with default values, using the copy-and-update facility of the record syntax

newSkirt = skirt { age=Adult }

and gender newSkirt evaluates to Female

I want to stress that this approach leads you to define default values at the type level, which I think is a Good Thing (of course the NoAge constructor is the Nothing of a Maybe Age type).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!