哪个是比喻字符和字符串的clojuresque方法?(单个字符串)

Alf*_*oli 28 string character clojure

我想知道在Clojure中比较字符和字符串的最佳(clojuresque)方法.显然,类似的东西会返回false:

(= (first "clojure") "c")
Run Code Online (Sandbox Code Playgroud)

因为first首先返回一个java.lang.Character,而"c"是一个单字符串.是否存在直接比较char和string而不调用强制转换的构造?我没有找到与此不同的方法:

(= (str (first "clojure")) "c")
Run Code Online (Sandbox Code Playgroud)

但我不满意.有任何想法吗?再见,阿尔弗雷多

kot*_*rak 42

直接串联互操作怎么样?

(= (.charAt "clojure" 0) \c)
Run Code Online (Sandbox Code Playgroud)

要么

(.startsWith "clojure" "c")
Run Code Online (Sandbox Code Playgroud)

它应该尽可能快,并且不会分配seq对象(在第二个示例中还有一个额外的字符串),它会立即再次丢弃,只是为了进行比较.

  • 我喜欢Clojure的是它不需要隐藏Java,所以+1. (5认同)

Jon*_*nas 23

字符文字是用\a \b \c ...Clojure 编写的,所以你可以简单地写

(= (first "clojure") \c)
Run Code Online (Sandbox Code Playgroud)


Art*_*ldt 6

字符串可以直接编入索引,而不构建从那时开始的序列并获取该序列的第一个.

(= (nth "clojure" 0) \c) 
=> true
Run Code Online (Sandbox Code Playgroud)

nth调用这个java代码:

static public Object nth(Object coll, int n){
    if(coll instanceof Indexed)
        return ((Indexed) coll).nth(n);    <-------
    return nthFrom(Util.ret1(coll, coll = null), n);
}
Run Code Online (Sandbox Code Playgroud)

它可以直接有效地读取字符.

首先调用这个java代码:

static public Object first(Object x){
    if(x instanceof ISeq)
        return ((ISeq) x).first();
    ISeq seq = seq(x);    <----- (1)
    if(seq == null)
        return null;
    return seq.first();   <------ (2)
}
Run Code Online (Sandbox Code Playgroud)

它为字符串(1)构建一个seq(构建一个seq非常快)然后从该seq(2)中获取第一个项目.返回后seq是垃圾.

Seqs显然是访问clojure中任何顺序的最自觉的方式,我根本就没有敲它们.有趣的是要知道你在创造什么.first通过调用切换所有调用nth可能是过早优化的情况.如果你想要字符串中的第100个字符,我建议使用像nth这样的索引访问函数

简而言之:不要出汗小东西:)