Removing vowels in clojure

I am trying to write a function to remove all ASCII vowels in Clojure. I am new to Clojure and I have slight string issues. For example, the string "hello world" will return "hll wrld" . I appreciate the help!

+4
source share
2 answers

To do this, you can use the basic functions of the string class.

 user=> (.replaceAll "hello world" "[aeiou]" "") "hll wrld" 

If this sounds like a trick, you can turn the string into seq and then filter it with the complement of the set and then put it back into the string.

 user=> (apply str (filter (complement #{\a \e \i \o \u}) (seq "hello world"))) "hll wrld" 

Kits in clojure are also features. complement takes a function and returns a function that returns a boolean function not from the original function. This is equivalent to this. apply takes a function and a bunch of arguments and calls that work with these arguments (roughly).

 user=> (apply str (filter #(not (#{\a \e \i \o \u} %)) (seq "hello world"))) "hll wrld" 

change

One more...

 user=> (apply str (re-seq #"[^aeiou]" "hello world")) "hll wrld" 

#"[^aeiou]" is a regular expression, and re-seq turns matches into seq. It is clojure-like and seems to work well. I can try this before moving on to Java. Those that seq lines are quite a bit slower.

Important change

There is another way, and you need to use clojure.string/replace . This might be the best way, given that it should work in either clojure or Clojurescript.

eg.

 dev:cljs.user=> (require '[clojure.string :as str]) nil dev:cljs.user=> (str/replace "hello world" #"[aeiou]" "") "hll wrld" 
+15
source

Bill is basically right, but erroneous enough to warrant this answer, I think.

 user=> (.replaceAll "hello world" "[aeiou]" "") "hll wrld" 

This solution is quite acceptable. This is actually the best solution. There is nothing wrong with abandoning Java if the solution is the cleanest and fastest.

Another solution, he said, uses sequence functions. However, its code is a bit strange. Never use filter with (not ..) or complement . There is a function for this, remove :

 user> (apply str (remove #{\a \e \i \o \u} "hello world")) "hll wrld" 

You also do not need to call seq in a string. All Clojure seq functions will handle this for you.

His last solution is interesting, but I would prefer the first one simply because it does not include (apply str ..) .

+8
source

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


All Articles