Skip to content

Commit

Permalink
core: Change to-num to return nil for nil or "x"
Browse files Browse the repository at this point in the history
  • Loading branch information
ingydotnet committed Sep 23, 2024
1 parent 8edf022 commit 2bed607
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
21 changes: 14 additions & 7 deletions core/src/ys/std.clj
Original file line number Diff line number Diff line change
Expand Up @@ -192,11 +192,10 @@
(cond
(ratio? x) (double x)
(number? x) x
(string? x) (or
(if (re-find #"\." x)
(parse-double x)
(parse-long x))
0)
(string? x) (if (re-find #"\." x)
(parse-double x)
(parse-long x))
(nil? x) nil
(seqable? x) (count x)
(char? x) (int x)
(boolean? x) (if x 1 0)
Expand Down Expand Up @@ -269,13 +268,21 @@
(cond
(number? x) (inc x)
(char? x) (char (inc (long x)))
:else (die "Cannot inc+(" (pr-str x) ")")))
:else (let [n (to-num x)]
(cond
(number? n) (inc n)
(nil? n) nil
:else (op-error "inc" x nil)))))

(defn dec+ [x]
(cond
(number? x) (dec x)
(char? x) (char (dec (long x)))
:else (die "Cannot dec+(" (pr-str x) ")")))
:else (let [n (to-num x)]
(cond
(number? n) (dec n)
(nil? n) nil
:else (op-error "dec" x nil)))))

(defn add+
([x y]
Expand Down
9 changes: 9 additions & 0 deletions ys/test/std.t
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,15 @@ test::
#-------------------------------------------------------------------------------
- note: "Common type conversion functions"

- code: to-num("42") == 42
- code: to-num(42) == 42
- code: to-num(1 .. 42) == 42
- code: to-num(set(1 .. 42)) == 42
- code: to-num(to-map(1 .. 42)) == 21
- code: to-num(to-vec(to-map(1 .. 42))) == 42
- code: to-num("") == nil
- code: to-num("xyz") == nil


#-------------------------------------------------------------------------------
- note: "Math functions"
Expand Down

0 comments on commit 2bed607

Please sign in to comment.