问题描述
榆树有“泛型”系统吗?
例如,我有一个函数说 setTime
获取记录并将 .date
更改为当前时间。
现在,如果我有多个带有 .date
的记录,我如何在多个不同的记录上使用相同的函数?
我尝试将签名设置为 a -> a
,但随后出现错误
Your type annotation uses type variable `a` which means ANY type of value
can flow through,but your code is saying it specifically wants a record. Maybe
change your type annotation to be more specific?
我可以让类型注释需要一个带有 .date
的记录吗?如果可以,怎么做?
解决方法
你可以写:
setTime : Date -> { a | date : Date } -> { a | date : Date }
其中 {a | data : Date}
表示 record
的任何值,其字段名为 date,其类型为 Date
。
如果您经常使用它并希望避免一些乏味,您也可以将该部分记录包装在类型别名中
type alias Dated a = { a | date : Date }setTime : Date -> Dated a -> Dated a
而且,你可以链接这些
type alias Dated a = { a | date : Date }
type alias Checked a { a | check : Bool }
checkAtTime : Date -> Dated (Checked a) -> Dated (Checked a)