Case for the first character of a string

I need to decide on a string based on the first character, and I have a method defined this way:

(defn check-first [string]
  (case (get string 0)
    "+" 1
    "-" 2
    3
    ))

Currently, it always returns 3, even when a string begins with these characters. What am I doing wrong? Also, is there a more elegant way to implement this?

+3
source share
3 answers
(get "foo" 0)
;; => \f

(get "foo" 0)returns a char, not string, so if you want to use check-first, you will need to replace the strings with characters.

(defn check-first [s]
  (case (first s) \+ 1, \- 2, 3))

By the way, Clojure library coding standards are  recommended sas an argument name for functions that require string input.

: (str (first "foo")) (subs "foo" 0 1) => "f"

case-indexed.

:

(defmacro case-indexed [expr & clauses]
  (list* 'case expr (interleave clauses (iterate inc 1))))

;; (case-indexed "foo" "bar" "baz" "foo") => 3
;; (case-indexed (+ 5 1) 3 4 5 6 7) => 4

(defn check-first [s]
  (case-indexed (first s)
    \+, \-, \*, \/))

, , , .

case-indexed , - . , check-first ; , . (, .)

+9

, , Java :

(defn check-first [s]
  (case (.substring s 0 1)
    "+" 1
    "-" 2
    3))

Edit: , MayDaniel subs, , .substring. , ...

+2

cond?

http://clojure-notes.rubylearning.org/

(def x 10)
(cond
(< x 0) (println "Negative!")
(= x 0) (println "Zero!"))
; => nil

(cond
(< x 0) (println "Negative!")
(= x 0) (println "Zero!")
:default (println "Positive!"))
; => Positive!
-3
source

Source: https://habr.com/ru/post/1766458/


All Articles