Loop in clojure with or condition - function

I'm trying to write a function in clojure that calls a condition for each value in a vector; the function should return the OR of the result of the condition applied to each value. Eg I have a vector [1 2 3 4] and a condition (>= x 3) where x is an element in the vector, then the function should return true (similary [0 1 0 1] should return false).
I wrote the method
(defn contains-value-greater-or-equal-to-three [values]
(or (for [x values] (>= x 3)))
)
but for the vector [1 2 3 4] this just yields (false false true true); what I want instead is the 'or' function applied to these values.
I'm quite new to functional programming and clojure, let me know if I'm thinking about this the wrong way.

Have a look at the function some, that takes a predicate and a collection as arguments, and returns true iff the predicate returns true for some item in the collection.
(some #(>= % 3) [1 2 3 4]) ; => true
(some #(>= % 3) [0 1 0 1]) ; => false
The problem with your method is that for returns a sequence of true/false values, while or expects a number of individual arguments. Given only one argument, or will return that. What you could have done is to reduce the sequence returned by for, like this:
(reduce #(or %1 %2) (for [x values] (>= x 3)))
(since or is a macro, not a function, (reduce or ...) will not work.

Related

How can a list or vector in Clojure be used to store and use functions?

Here is what I tried in the REPL.
(def mstuffs [(fn [n] (* 1 n)) (fn [n] (* 1 n))])
((mstuffs first) 2)
Here is the error I got
; Execution error (IllegalArgumentException) at nrepl.middleware.interruptible-eval/evaluate$fn$fn (interruptible_eval.clj:87).
; Key must be integer
What am I doing wrong?
Vectors in clojure are functions from index to to the corresponding item e.g.
([:foo :bar :baz] 1)
=> :bar
so (mstuffs first) is trying to index the vector mstuffs with the argument first. Since first is a function not an integer you get the resulting exception. It looks like you mean to invoke the first function in the vector so should use
((first mstuffs) 2)

Wrong arity of simple function in clojure

I've started to learn clojure. In my book there is following exercise:
Write a function, mapset, that works like map except the return value is a set:
(mapset inc [1 1 2 2])
; => #{2 3}
I've started with something like this:
(defn mapset
[vect]
(set vect))
The result is error
"Wrong number of args (2) passed to: core/mapset"
I tried [& args] as well.
So, the question is: how can I solve such problem?
Take a closer look at your call to mapset:
(mapset inc [1 1 2 2])
Since code is data, this "call" is just a list of three elements:
The symbol mapset
The symbol inc
The vector [1 1 2 2]
When you evaluate this code, Clojure will see that it is a list and proceed to evaluate each of the items in that list (once it determines that it isn't a special form or macro), so it will then have a new list of three elements:
The function to which the symbol core/mapset was bound
The function to which the symbol clojure.core/inc was bound
The vector [1 1 2 2]
Finally, Clojure will call the first element of the list with the rest of the elements as arguments. In this case, there are two arguments in the rest of the list, but in your function definition, you only accounted for one:
(defn mapset
[vect]
(set vect))
To remedy this, you could implement mapset as follows:
(defn mapset
[f vect]
(set (map f vect)))
Now, when you call (mapset inc [1 1 2 2]), the argument f will be found to the function clojure.core/inc, and the argument vect will be bound to the vector [1 1 2 2].
Your definition of mapset takes a single argument vect
At a minimum you need to take 2 arguments, a function and a sequence
(defn mapset [f xs] (set (map f xs)))`
But it is interesting to think about this as the composition of 2 functions also:
(def mapset (comp set map))

Define a function, call it ‘CHECK’ in scheme

how to write this in scheme?
Define a function, call it ‘CHECK’ that takes an integer as its first argument, a list of integers
as its second argument and returns the count of how many times the first argument appears in the second
What you are describing is a variation of what is usually called `count':
(define (check num ls) (count (lambda (val) (= val num)) ls))
(check 2 '(2 3 4 2)) ; => 2

return vector without nth element (complement of (nth))

I need to get a random value from a vector of integers.
I also need to get back the vector without the value key.
Example code is below. I know I can easily put this code in a function to reuse.
But wonder if there is some function or a better way to create a new vector without the nth element? (thus the complement of the (nth) function in core clojure)
(let [ vector [1 2 3 5 9 1]
id (rand-int (count vector))
value (nth vector id)
head (take id vector)
tail (drop (+ id 1) vector)
vector (flatten [head tail])]
{:value value :new-vector vector})
The vector data structure cannot efficiently remove a single element. If you are doing this often, you should generally be using a more suitable data structure. For example, if the elements of your vector are distinct, you could use a set (or sorted-set, if order is important to you in other cases). Or if they're not distinct, but you never care about order, you can do a Fisher-Yates shuffle - here we use a vector, but avoid the "removing from the middle is expensive" problem by swapping one in the middle with the element on the end, and then removing from the end instead.
Heed #amalloy's advice but if you still want to create a function you can do something like this
(defn sans-nth [v idx]
"Takes in a vector and an index.
Returns value at index and removes value from vector"
(let [x (get #v idx)
y #(vec (concat (take idx %) (drop (inc idx) %)))]
(swap! v y)
x))
Example
(def v (atom [1 2 3 4 5 6]))
'user/v
(sans-nth v 3)
4
#v
[1 2 3 5 6]
If you need to just remove an element from a vector
(defn remove-nth [v i]
(vec (concat (take i v) (drop (inc i) v))))

Defining a Racket Function?

I'm supposed to define the function n! (N-Factorial). The thing is I don't know how to.
Here is what I have so far, can someone please help with this? I don't understand the conditionals in Racket, so an explanation would be great!
(define fact (lambda (n) (if (> n 0)) (* n < n)))
You'll have to take a good look at the documentation first, this is a very simple example but you have to understand the basics before attempting a solution, and make sure you know how to write a recursive procedure. Some comments:
(define fact
(lambda (n)
(if (> n 0)
; a conditional must have two parts:
; where is the consequent? here goes the advance of the recursion
; where is the alternative? here goes the base case of the recursion
)
(* n < n))) ; this line is outside the conditional, and it's just wrong
Notice that the last expression is incorrect, I don't know what it's supposed to do, but as it is it'll raise an error. Delete it, and concentrate on writing the body of the conditional.
The trick with scheme (or lisp) is to understand each little bit between each set of brackets as you build them up into more complex forms.
So lets start with the conditionals. if takes 3 arguments. It evaluates the first, and if that's true, if returns the second, and if the first argument is false it returns the third.
(if #t "some value" "some other value") ; => "some value"
(if #f "some value" "some other value") ; => "some other value"
(if (<= 1 0) "done" "go again") ; => "go again"
cond would work too - you can read the racket introduction to conditionals here: http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Conditionals_with_if__and__or__and_cond%29
You can define functions in two different ways. You're using the anonymous function approach, which is fine, but you don't need a lambda in this case, so the simpler syntax is:
(define (function-name arguments) result)
For example:
(define (previous-number n)
(- n 1))
(previous-number 3) ; => 2
Using a lambda like you have achieves the same thing, using different syntax (don't worry about any other differences for now):
(define previous-number* (lambda (n) (- n 1)))
(previous-number* 3) ; => 2
By the way - that '*' is just another character in that name, nothing special (see http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Identifiers%29). A '!' at the end of a function name often means that that function has side effects, but n! is a fine name for your function in this case.
So lets go back to your original question and put the function definition and conditional together. We'll use the "recurrence relation" from the wiki definition because it makes for a nice recursive function: If n is less than 1, then the factorial is 1. Otherwise, the factorial is n times the factorial of one less than n. In code, that looks like:
(define (n! n)
(if (<= n 1) ; If n is less than 1,
1 ; then the factorial is 1
(* n (n! (- n 1))))) ; Otherwise, the factorial is n times the factorial of one less than n.
That last clause is a little denser than I'd like, so lets just work though it down for n = 2:
(define n 2)
(* n (n! (- n 1)))
; =>
(* 2 (n! (- 2 1)))
(* 2 (n! 1))
(* 2 1)
2
Also, if you're using Racket, it's really easy to confirm that it's working as we expect:
(check-expect (n! 0) 1)
(check-expect (n! 1) 1)
(check-expect (n! 20) 2432902008176640000)