当前位置: 首页 > 文档资料 > Clojure 入门教程 >

23.3 Validation函数

优质
小牛编辑
128浏览
2023-12-01

Validation函数

在继续介绍下一个引用类型之前,下面是一个validation函数的例子,他验证所有赋给Ref的值是数字。

; Note the use of the :validator directive when creating the Ref
; to assign a validation function which is integer? in this case.
(def my-ref (ref 0 :validator integer?))

(try
  (dosync
    (ref-set my-ref 1) ; works

    ; The next line doesn't work, so the transaction is rolled back
    ; and the previous change isn't committed.
    (ref-set my-ref "foo"))
  (catch IllegalStateException e
    ; do nothing
    ))

(println "my-ref =" @my-ref) ; due to validation failure -> 0