Clojure:从地图创建记录时确保数据完整性? [英] Clojure: Ensure data integrity when creating a Record from a Map?

查看:101
本文介绍了Clojure:从地图创建记录时确保数据完整性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Clojure并很喜欢它,但是发现Records中的不一致之处令我感到困惑:为什么默认的地图构造函数(map-> Whatever)在创建新Record时不检查数据完整性?例如:

I'm learning Clojure and enjoying it but find an inconsistency in Records that puzzles me: why doesn't the default map constructor (map->Whatever) check for data integrity when creating a new Record? For instance:

user=> (defrecord Person [first-name last-name])
#<Class@46ffda99 user.Person>
user=> (map->Person {:first-name "Rich" :last-name "Hickey"})
#user.Person {:first-name "Rich" :last-name "Hickey"}
user=> (map->Person {:first-game "Rich" :last-name "Hickey"})
#user.Person {:first-game "Rich" :first-name nil :last-name "Hickey"}

我认为地图不需要定义Record定义中的所有字段,还允许包含不属于Record定义的其他字段。我也知道我可以定义自己的构造函数,该构造函数包装默认的构造函数,然后我认为:post 条件可以用于检查记录的正确(且全面)(

I believe the Map is not required to define all the fields in the Record definition and it is also allowed to contain extra fields that aren't part of the Record definition. Also I understand that I can define my own constructor which wraps the default constructor and I think a :post condition can then be used to check for correct (and comprehensive) Record creation (have not been successful in getting that to work).

我的问题是:是否有一种惯用的Clojure方法在从地图构建记录期间验证数据?而且,关于记录,我在这里缺少什么吗?

My question is: Is there an idiomatic Clojure way to verify data during Record construction from a Map? And, is there something that I'm missing here about Records?

谢谢。

推荐答案

我认为您的全面性要求已经非常具体了,因此我所了解的内置内容无法涵盖这一切。

I think your comprehensiveness requirement is already quite specific, so nothing built-in I know of covers this.

如今您可以做的一件事是使用clojure.spec为构造函数提供 s / fdef (然后进行检测)。

One thing you can do nowadays is use clojure.spec to provide an s/fdef for your constructor function (and then instrument it).

(require '[clojure.spec.alpha :as s]
         '[clojure.spec.test.alpha :as stest])

(defrecord Person [first-name last-name])

(s/fdef map->Person
  :args (s/cat :map (s/keys :req-un [::first-name ::last-name])))

(stest/instrument `map->Person)

(map->Person {:first-name "Rich", :last-name "Hickey"})
(map->Person {:first-game "Rich", :last-name "Hickey"})  ; now fails

(如果为 :: first-name定义了规范 :: lastname 也会被选中。)

(If specs are defined for ::first-name and ::last-name those will be checked as well.)

这篇关于Clojure:从地图创建记录时确保数据完整性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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