Blaine Lafreniere
Blaine Lafreniere

Reputation: 3600

What is the Clojure equivalent of Ruby's select?

I want to return a list/collection of all numbers in a range that are a multiple of 3 or 5.

In Ruby, I would do

(1..1000).select {|e| e % 3 == 0 || e % 5 == 0}

In Clojure, I'm thinking I might do something like...

(select (mod 5 ...x?) (range 0 1000))

Upvotes: 3

Views: 452

Answers (4)

bOR_
bOR_

Reputation: 381

A different way is to generate the solution, rather than to filter for it:

(set (concat (range 0 1000 3) (range 0 1000 5)))

Upvotes: 5

Jed Schneider
Jed Schneider

Reputation: 14671

how about this: http://gist.github.com/456486

Upvotes: 1

Rayne
Rayne

Reputation: 32625

(filter #(or (= (mod % 5) 0) (= (mod % 3) 0)) (range 1 100))

is the most direct translation.

(for [x (range 1 100) :when (or (= (mod x 5) 0) (= (mod x 3) 0))] x)

is another way to do it.

Instead of doing (= .. 0), you can use the zero? function instead. Here is the amended solution:

(filter #(or (zero? (mod % 5)) (zero? (mod % 3))) (range 1 100))

Upvotes: 3

dbyrne
dbyrne

Reputation: 61011

(filter #(or (zero? (mod % 3)) (zero? (mod % 5))) (range 1000))

Upvotes: 5

Related Questions