简体   繁体   English

如何在Clojure中使用谓词?

[英]How do I use predicates in clojure?

I'm kinda new to clojure and I am unsure of how to use predicates. 我对Clojure有点陌生,我不确定如何使用谓词。 For instance, how do I make a function that returns the elements in a list that satisfies the predicate. 例如,我如何制作一个函数,该函数返回满足谓词的列表中的元素。

>(filter-in number? '(a 2 (1 3) b 7))
 (2 7)

 >filter in symbol? '(a (b c) 17 foo))
 (a foo)

I tried this but it does not work: 我试过了,但是不起作用:

(defn filter-in [pred lst]
   (fn [x]
     (if (empty? lst)
       ()
       (if (pred (first lst))
         (cons (first lst) (filter-in pred (rest lst)))
         (filter-in pred (rest lst))))))

Thanks in advance. 提前致谢。

As @Deigo_Basch points out in the comments, Clojure already has a built-in function 'filter' that does what you want. 正如@Deigo_Basch在评论中指出的那样,Clojure已经具有内置的“过滤器”功能,可以满足您的需求。

However, if you're trying to create your own to help with your learning process, your solution is almost there: 但是,如果您想创建自己的学习过程来帮助自己,那么您的解决方案就差不多了:

(defn filter-in [pred lst]
     (if (empty? lst)
       '()
       (if (pred (first lst))
         (cons (first lst) (filter-in pred (rest lst)))
         (filter-in pred (rest lst)))))

Your original solution was actually defining a function that returned another function (the 'fn [x]' part). 您最初的解决方案实际上是定义一个函数,该函数返回另一个函数(“ fn [x]”部分)。 Higher-level functions like that that return other functions are often useful, but in this case you are looking for something that executes on its arguments directly. 像这样的返回其他函数的高级函数通常很有用,但是在这种情况下,您正在寻找直接在其参数上执行的东西。

Note also that your definition is not lazy, unlike Clojure's built-in filter. 还请注意,与Clojure的内置过滤器不同,您的定义并不懒惰。 It also does not make use of Clojure's loop-recur mechanics, and thus may blow up the stack on large lists. 它还没有利用Clojure的循环递归机制,因此可能会炸毁大型列表上的堆栈。 These are features of Clojure that you will encounter soon as you learn more. 这些是Clojure的功能,一旦您了解更多,就会很快遇到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM