Man*_*tis 3 string case clojure
我需要根据第一个字符做出关于字符串的决定,并且我有一个以这种方式定义的方法:
(defn check-first [string]
(case (get string 0)
"+" 1
"-" 2
3
))
Run Code Online (Sandbox Code Playgroud)
目前,即使字符串以这些字符开头,它也始终返回3.我究竟做错了什么?另外,有更优雅的方式来实现这个吗?
May*_*iel 10
(get "foo" 0)
;; => \f
Run Code Online (Sandbox Code Playgroud)
(get "foo" 0)
返回a char
,而不是a string
,所以,如果你想使用你的check-first
,你需要用字符替换字符串.
(defn check-first [s]
(case (first s) \+ 1, \- 2, 3))
Run Code Online (Sandbox Code Playgroud)
顺便说一下,Clojure Library Coding Standards
建议使用s
作为需要字符串输入的函数的参数名称.
如果您更喜欢使用字符串代替字符:(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)
\+, \-, \*, \/))
Run Code Online (Sandbox Code Playgroud)
我不认为我会将这样的条款分开 - 这只是为了让答案更加简洁.
case-indexed
不过,如果要使用它,我建议扩展默认表达式.此外,check-first
这个功能的名称似乎过于笼统; 我没有更好的建议,但我会考虑改变它.(假设它不是为了这个问题而编造的.)
归档时间: |
|
查看次数: |
3371 次 |
最近记录: |