Fork me on GitHub
#clojure-spec
<
2017-01-03
>
curlyfry13:01:28

What is the best way to spec a string that contains a floating point number? Using a regex or some other method?

mpenet13:01:50

Float/parseFloat comes to mind

curlyfry13:01:43

So what would the spec look like? In particular, would I have to write a custom generator?

donaldball13:01:33

It might look like: (s/spec #(Double/parseDouble %) :gen (gen/fmap str (gen/double)))

donaldball14:01:31

Possibly using gen/double* with some constraints

curlyfry14:01:45

@donaldball Cool, thanks! Unfortunately I'm in cljs-land, so I think I might have to go the regex path anyway

dialelo14:01:35

maybe js/parseFloat can help then @curlyfry

curlyfry14:01:32

Just one more thing: When you make a spec like (s/def ::double-string #(Double/parseDouble %)) we rely on parseDouble throwing an exception rather than matching a certain predicate, right?

curlyfry14:01:23

js/parseFloat is a bit too forgiving: (js/parseFloat "1.23abcdef") => 1.23

curlyfry14:01:24

Ended up with:

(def decimal-regex #"-?\d+\.\d+")
(s/def ::double-string (s/spec (s/and string? #(re-matches decimal-regex %)) :gen #(gen/fmap str (gen/double))))
Anything that could be written in a nicer way?

mpenet14:01:26

if you end up doing that a lot (specing via regex) you might want to check test.chuck for the gen part

mpenet14:01:31

especially test.chuck.generators/string-from-regex

mpenet14:01:00

I've thrown crazy regexes at it and it never failed me (so far)

joshjones15:01:11

@curlyfry not saying a nicer way doesn’t exist, but that way is straightforward and works well, and it’s the way i’d do it

roelof15:01:37

@seancorfield I know that you answered it with I think a namespace and a function ( artObjects-id:response ) but when I used it in a sdef I did not work