Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure recursive function

As a Clojure newbie, I'm bothered with this small problem:

I would like to iterate through a sequence and execute a split, and then a str (concatenation) function over the sequence elements.

Here is my sequence:

(("2.660.784") ("2.944.552") ("44.858.797"))

What I want to get is something like this:

("2660784" "2944552" "44858797")

And this is my attempt of creating recursive solution for my problem:

(defn old 
      [squence]
      (let [size (count squence)]
        (loop [counter 1]
          (if (<= counter size)
            (apply str (clojure.string/split 
                   (first (first squence))
                   #"\b\.\b"
                   ))
            (old (rest squence)))
          )))

And of course, this is not a solution because it applies split and str only to one element, but I would like to repeat this for each element in squence. The squence is product of some other function in my project.

I'm definitely missing something so please help me out with this one...

like image 881
Мitke Avatar asked Dec 06 '25 10:12

Мitke


2 Answers

The simplest way to write it is with replace, rather than split/str. And once you've written a function that can do this transformation on a single string, you can use map or for to do it to a sequence of strings. Here I had to destructure a bit, since for whatever reason each element of your sequence is itself another sequence; I just pulled out the first element.

(for [[s] '(("2.660.784") ("2.944.552") ("44.858.797"))]
  (clojure.string/replace s #"\b\.\b" ""))
like image 96
amalloy Avatar answered Dec 08 '25 03:12

amalloy


user=> (defn reject-char-from-string
  [ch sequence]
  (map #(apply str (replace {ch nil} (first %))) sequence))
#'user/reject-char-from-string
user=> (reject-char-from-string \. '(("2.660.784") ("2.944.552") ("44.858.797"))
)
("2660784" "2944552" "44858797")
like image 23
BLUEPIXY Avatar answered Dec 08 '25 03:12

BLUEPIXY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!