开发者

Clojure recursive function

开发者 https://www.devze.com 2023-04-13 04:56 出处:网络
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开发者_运

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...


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" ""))


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")


Tried this?

=> (flatten '(("2.660.784") ("2.944.552") ("44.858.797")))
("2.660.784" "2.944.552" "44.858.797")


Is it as simple as this?

(def data '(("2.660.784") ("2.944.552") ("44.858.797")))
(require '[clojure.string :as string])
(map #(string/replace (first %1) "." "") data)
;=> ("2660784" "2944552" "44858797")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号