Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move parameter in Clojure function

Tags:

clojure

I'm working on 4clojure problem 29 : "Get the Caps"

(= (__ "HeLlO, WoRlD!") "HLOWRD")

I've written a solution in the REPL:

user=> (apply str (filter (fn [foo] (some #(= % foo) 
         (map char (range 65 91)))) "AbC"))
"AC"

But as you can see my parameter "AbC" is nested two parentheses in. How would I move my parameter to the outside so I can use it in the 4clojure test? Have I approached the problem in the wrong way?

like image 831
Sonia Hamilton Avatar asked Dec 28 '22 01:12

Sonia Hamilton


1 Answers

You don't need to move the a parameter to the outside, you can just use the same technique you used to create the filtering function, that is, with fn:

(fn [string] 
  (apply str 
    (filter 
      (fn [foo] (some #(= % foo) (map char (range 65 91)))) 
      string)))

As an example of this, the following two statements are the same:

(+ 1 2 3)
((fn [n] (+ 1 2 n)) 3)

However, to actually answer your question, you could use comp ("compose") and partial to move the parameter to allow eta conversion (that is the technical name for the last part of the manipulation you are attempting to do):

(comp (partial apply str)
      (partial filter (fn [foo] (some #(= % foo) 
                                       (map char (range 65 91))))))

This expression is now a function that takes a string, filters the capital letters and then converts it back to a string (notices that comp applies functions from right to left).

(NB, that last expression probably isn't very idiomatic Clojure; the first method, or one of the suggestions of others, is better.)

like image 162
huon Avatar answered Jan 14 '23 17:01

huon