这是错误吗?尝试从包含nil

时间:2018-10-07 09:52:32

标签: clojure nullpointerexception clojure.spec

我找到了一种通过使用s/or规范生成值来引发NullPointerExceptions的方法。我希望能够生成并标记一个nil值,没有s/nilable是不合适的。

这是clojure.spec中的错误吗?

(ns blah
  (:require [clojure.spec.alpha :as s])) 

(s/def ::fine (s/or :int int? :nil nil?)
(s/def ::throws (s/or :int (s/int-in 1 5) :zero zero? :nil nil?)

(s/exercise ::fine)
=>
([nil [:nil nil]
 [-1 [:int -1]]
 [nil [:nil nil]]
 [0 [:int 0]]
 [nil [:nil nil]]
 [15 [:int 15]]
 [-25 [:int -25]]
 [nil [:nil nil]]
 [-2 [:int -2]]
 [-30 [:int -30]]])]])

(s/exercise ::throws)
=>
NullPointerException   clojure.lang.Numbers.ops (Numbers.java:1018)

如果您限制执行::throws的次数,则会看到正确的:int:zero值,而引发的是:nil

1 个答案:

答案 0 :(得分:2)

这有效:

$inputext = "Those terms can be Blue Restaurant Ocean/Blue Restaurant, Blue's Restaurant."; 

// you put your phrases here, remember to escape
// double quote if you want to use it as phrase
$termList = [
    "Ocean Restaurant",
    "Ocean/Blue Restaurant",
    "Blue Restaurant",
    "Blue's Restaurant",
    "so called \"double quote\" probably",
];

$esc = function(string $input) : string
{
    return '(' . preg_quote($input, '/') . ')';
};

$termEscapedList = array_map($esc, $termList);
$pattern = implode('|', $termEscapedList);

$rule = '/' . $pattern . '/i';
$replacetext = "[X]";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo $outputext,"\n";

我认为规格将按照(s/def ::works (s/or :int (s/int-in 1 5) :nil nil? :zero zero?)) 替代的顺序进行尝试。使用or谓词使nil符合条件将会崩溃,但是将zero?置于其谓词前面将防止这种情况的发生。

同样有效的是使用集合而不是谓词:

nil?