programming-beginners 2018-03-09

@jr0cket has joined the channel

New question. Why does this:

(def names ["Amelia Cook" "Natalie Bell"])

(defn split [x] (clojure.string/split x #" "))

(split names)
Return this ["[\"Amelia" "Cook\"" "\"Natalie" "Bell\"]"]?

What I want is obviously "Amelia" "Cook" "Natalie" "Bell" but I can’t figure out why it’s doing this so I can try to understand how to fix it.

=> (doc clojure.string/split)
-------------------------
clojure.string/split
([s re] [s re limit])
  Splits string on a regular expression.  Optional argument limit is
  the maximum number of splits. Not lazy. Returns vector of the splits.
nil
split expects a string, so it coerces whatever you pass it into a string

=> (str ["a" "b" "c"])
"[\"a\" \"b\" \"c\"]"

So when I define the names I shouldn’t put it into a vector?

@amelia that’s not valid clojure, are you running clojurescript?

if you try that in a clojure repl you’ll get an error

saying that a vector is not a string

it's fine to put them into a vector, but you cannot call split on that vector

since you want to apply it to the strings inside the vector, use split with map: (map split names)

Thank you! I’ll give it a try

It worked! 😄 Thank you!

@amelia note that if you want to have all the splitted strings returned in a single collection, you can replace the map with mapcat:

=> (map (fn [s] (clojure.string/split s #" ")) ["a b" "c d"])
(["a" "b"] ["c" "d"])
=> (mapcat (fn [s] (clojure.string/split s #" ")) ["a b" "c d"])
("a" "b" "c" "d")

Haha, I was just looking for something like that - thanks again!

👍🏼 1

@magra has left the channel

Why does everyone keep using foo in examples?

when people want to express abstract concepts in code (such as in examples) the name of variables don’t matter as they don’t mean anything

so we usually use “foo” “bar” “baz” “fred” and others

to mean “this is a variable that we don’t really care what its name should be”

"qux" is another one

I am really glad this channel exists, no way I could ask this kind of thing in #beginners

👍🏼 5