How to resolve the algorithm Determine if a string is numeric step by step in the Clojure programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Determine if a string is numeric step by step in the Clojure programming language
Table of Contents
Problem Statement
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Determine if a string is numeric step by step in the Clojure programming language
Source code in the clojure programming language
(defn numeric? [s]
(if-let [s (seq s)]
(let [s (if (= (first s) \-) (next s) s)
s (drop-while #(Character/isDigit %) s)
s (if (= (first s) \.) (next s) s)
s (drop-while #(Character/isDigit %) s)]
(empty? s))))
(numeric? [\1 \2 \3]) ;; yields logical true
(require '[clojure.edn :as edn])
(import [java.io PushbackReader StringReader])
(defn number-string? [s]
(boolean
(when (and (string? s) (re-matches #"^[+-]?\d.*" s))
(let [reader (PushbackReader. (StringReader. s))
num (try (edn/read reader) (catch Exception _ nil))]
(when num
; Check that the string has nothing after the number
(= -1 (.read reader)))))))
user=> (number-string? "2r101010")
true
user=> (number-string? "22/7")
true
You may also check:How to resolve the algorithm Quine step by step in the Visual Basic .NET programming language
You may also check:How to resolve the algorithm Taxicab numbers step by step in the J programming language
You may also check:How to resolve the algorithm Power set step by step in the PowerShell programming language
You may also check:How to resolve the algorithm User input/Text step by step in the Axe programming language
You may also check:How to resolve the algorithm Sleep step by step in the Phix programming language