longs functiooon cloj - clojure

I'm trying to use the longs function, but it's not working:
(println (longs 1 2 3))
Any examples?
The description in the site is not very good, which is why I'm having problems
http://clojure.org/cheatsheet
Thanks

You're question is woefully incomplete, but I'll take a stab at it anyway.
The documentation for longs says:
Usage: (longs xs)
That means, it's expecting one argument (named xs in this example). You're passing it three arguments.
The documentation for longs continues thus:
Casts to long[]
Casting means: It doesn't change xs, it simply checks that it is an array of primitive long and then make this information available to the compiler. Basically, wrapping an expression that produces a long[] in (longs ...) is a type hint for Clojure so that it doesn't have to use reflection at runtime to resolve a method call using that value as an argument:
// Suppose we have a java class
class JavaClass {
static long[] getSomeLongs() { ... }
static long sum(long[] numbers) { ... }
static float sum(float[] numbers) { ... }
}
;; And this Clojure code:
(defn numbers [] (JavaClass/getSomeLongs))
(JavaClass/sum (numbers))
Clojure is dynamically typed, so when it compiles the second line, it won't know that (numbers) returns an array of long. It will have to wait until run time and then look up the correct JavaClass/sum method using reflection. This is expensive.
The solution is to give the Clojure compiler a hint about the type of (numbers). That way it can choose the correct method to call at compile time, resulting in a faster running program:
(JavaClass/sum (longs (numbers)))
But, judging from your woefully incomplete question, that's probably not what you were expecting when you reached for longs. It seems you were hoping it would create an array of longs from the arguments you gave it. If that's what you want then use this:
(into-array Long/TYPE [1 2 3])
But, you're likely to be disappointed by the results of printing it:
user=> (println (into-array Long/TYPE [1 2 3]))
#<long[] [J#2321b59a>
That's what Java gives back when you ask it to convert an array into a String, so that's what Clojure prints. If you want to see the contents of the array printed back, you need to make a sequence:
user=> (println (seq (into-array Long/TYPE [1 2 3])))
(1 2 3)

Related

Clojure - Creating a No Divisors function

I am really struggling to do this one function. The function is as follows
Write a function named no-divisors? which takes an input n. The function should return true if none of the numbers between 2 and √𝑛 divide n, and false otherwise. The function should use both your get-divisors function and your divides? function.
Hint: you will probably need to wrap the divides? function in an anonymous function so that you can pass in the value of n.
This is my get-divisors function:
(defn get-divisors [n]
(str (range 2 (inc (Math/floor (Math/sqrt n))))))
This is my divides? function:
(defn divide [a b]
(zero? (mod a b)))
I have tried to create a method in order to try and complete this task, however, to no luck.
This is what I tried:
(defn no-divisors [n]
divide(n (get-divisors n)))
And I received the output:
ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn user/x (form-init5516475059937019181.clj:16)`
I have an idea in mind which I would like to share of how I could create this task, however, since this is my first time using Clojure I am not too sure of to implement this function or if it is even possible. I am extremely sorry that I have mixed syntax, it's just I have never used Clojure up until this point, but here is my draft/blueprint:
(defn no-divisors [n]
resultsArray = []
def results((get-divisors n))
for results in get-divisors
resultsArray.append(results)
for i=results[0]; i< results.count; i++
divide(n i)
)
I maybe on the right path or probably (most likely) completely wrong. I am grateful and thankful for any/all help I can possibly receive. Just a side note, both my get-divisors and divides? functions work flawlessly.
Firstly, you can't just put parentheses anywhere in the code like you can in other languages. They mean something specific in Clojure (and other lisps) when evaluating code, namely the first thing in the list is a verb; a function to call. Nested brackets mean repeated calls to the result of a function. So if you have a function alice that returns a function, like this (stay with me, I'm trying to explain the error you're getting ;) ):
(defn alice []
(fn [] :bob))
then you can call it like this
(alice) ;; => #function[user/alice/fn--6930]
and it will return the function that you have created inside, and you can call that anonymous function like this:
((alice)) ;; => :bob
to actually get the result of that function. Apologies if this is a bit much off the bat, but the parens have meaning, and that's the cause of the error you're getting:
ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn
This means that you're trying to call a number as a function. clojure.lang.IFn is Clojure's way of saying "the thing I was expecting was something that I could call as a function". By java.lang.Long, Clojure's mean's "number". ClassCastException means I saw one thing and was expecting the other. So really, what this error is trying to say is you wrote an open paren ( and followed that up with something named a number and not a function. That seems very much like you've written divide(n (get-divisors n)) instead of (divide n (get-divisors n)), because when evaluating divide(n (get-divisors n)) it first tries to evaluate divide and discovers this is a function, but doesn't try and call it. Then it looks at the next form (n (get-divisors n)) and tries asks what n is, and finds it's a number, which can't be called as a function. Make sense?
In your pseudo-code, you have an array that you append data to to collect the results while iterate through a loop to build the results. This is a very imperative way of approaching the problem, and not really the way Clojure is trying to encourage you to solve problems. Clojure tends to learn towards a more data focused way of solving the problem. One way to think about the problem is the way in which it's phrased in English. Given a number n, take all the numbers less than the square-root of it, and check if they divide into n. If that list is empty return true, otherwise return false. In Clojure you could write:
(defn divide? [a b]
(zero? (mod a b)))
(defn no-divisors? [n]
(->> (range 2 n)
(take-while #(< (* % %) n))
(filter (partial divide? n))
empty?))
Here, we use the ->> macro to take a lazy sequence of numbers between 2 and n, then limit that sequence using take-while to only the ones where the square of the number is less than n. Then we check that each one divides into n using the divide? function, and finally ask if the list is empty?. Since Clojure's sequences are lazy, no actual computation occurs until we try to evaluate the result using empty? which will stop when it reaches an element in the sequence. This makes it more efficient than actually traversing the whole list for large values of n.
Hope this helps.
P.S. I'm not sure your implementation of get-divisors is quite correct.
You must test your work as you go along. Let's look at your get-divisors function:
(defn get-divisors [n]
(str (range 2 (inc (Math/floor (Math/sqrt n))))))
Let's try it:
=> (get-divisors 20)
"(2 3 4)"
This is a string of characters, not the collection of numbers it ought to be. Remove the damaging str call:
(defn get-divisors [n]
(range 2 (inc (Math/floor (Math/sqrt n)))))
Now
=> (get-divisors 20)
(2 3 4)
Good. And an edge case, just to make sure:
=> (get-divisors 16)
(2 3 4)
Good again! We can use this function with some confidence.
Now we want to find out whether something is true of none of this collection. There's a handy function called not-any? that does this. For example,
=> (not-any? even? (range 1 100 2))
true
What we want to determine is whether none of the potential divisors of n actually divide n. So the shape of the function might be ...

Why `clojure.set/union` function accept other type of data as input?

I'm learning Clojure and I found something surprised me, as mentioned in title. As doc said, the clojure.set/union function
Return a set that is the union of the input sets
However I tried to input other type sequences and it gives me some result instead of telling me the input type is wrong. For example
user=> (clojure.set/union '(1 2 3) '(2 3 4))
(4 3 2 1 2 3)
Here I expected Clojure to warn me my inputs are not sets, but it returns another list with duplicate inside, which is also opposite to what is stated in document("Return a set").
I'm wondering why this function is designed like this and what benefits it provides than giving a type error. Thanks in advance!
While I would prefer to see more type checking, Clojure often adopts a "garbage in, garbage out" type of philosophy. In this example, it extends to assuming that you provide 2 sets to the union function.
Looking at the source:
(defn union
"Return a set that is the union of the input sets"
[s1 s2]
(if (< (count s1) (count s2))
(reduce conj s2 s1)
(reduce conj s1 s2)))
you can see it simply appends the shorter input onto the longer input using conj. For a sequential list or vector, this adds the 2nd list of items (one at a time) to the front of the 1st list, which your example shows.

Arrays and loops in Clojure

I am trying to learn the programming language Clojure. I have a hard time understanding it though. I would like to try to implement something as simple as this (for example):
int[] array = new int[10];
array[0] =1;
int n = 10;
for(int i = 0; i <= n; i++){
array[i] = 0;
}
return array[n];
Since I am new to Clojure, I don't even understand how to implement this. It would be super helpful if someone could explain or give a similar example of how arrays/for-loops works in Clojure. I've tried to do some research, but as for my understanding Clojure doesn't really have for-loops.
The Clojure way to write the Java for loop you wrote is to do consider why you're looping in the first place. There are many options for porting a Java loop to Clojure. Choosing among them depends on what your goal is.
Ways to Make Ten Zeroes
As Carcigenicate posted, if you need ten zeros in a collection, consider:
(repeat 10 0)
That returns a sequence – a lazy one. Sequences are one of Clojure's central abstractions. If instead the ten zeros need to be accessible by index, put them in a vector with:
(vec (repeat 10 0))
or
(into [] (repeat 10 0))
Or, you could just write the vector literal directly in your code:
[0 0 0 0 0 0 0 0 0 0]
And if you specifically need a Java array for some reason, then you can do that with to-array:
(to-array (repeat 10 0))
But remember the advice from the Clojure reference docs on Java interop:
Clojure supports the creation, reading and modification of Java arrays [but] it is recommended that you limit use of arrays to interop with Java libraries that require them as arguments or use them as return values.
Those docs list some functions for working with Java arrays primarily when they're required for Java interop or "to support mutation or higher performance operations". In nearly all cases Clojurists just use a vector.
Looping in Clojure
What if you're doing something other than producing ten zeros? The Clojure way to "loop" depends on what you need.
You may need recursion, for which Clojure has loop/recur:
(loop [x 10]
(when-not (= x 0)
(recur (- x 2))))
You may need to calculate a value for every value in some collection(s):
(for [x coll])
(calculate-y x))
You might need to iterate over multiple collections, similar to nested loops in Java:
(for [x ['a 'b 'c]
y [1 2 3]]
(foo x y))
If you just need to produce a side effect some number of times, repeatedly is your jam:
(repeatedly 10 some-fn)
If you need to produce a side effect for each value in a collection, try doseq:
(doseq [x coll]
(do-some-side-effect! x))
If you need to produce a side effect for a range of integers, you could use doseq like this:
(doseq [x (range 10)]
(do-something! x))
...but dotimes is like doseq with a built-in range:
(dotimes [x 9]
(do-something! x))
Even more common than those loopy constructs are Clojure functions which produce a value for every element in a collection, such as map and its relatives, or which iterate over collections either for special purposes (like filter and remove) or to create some new value or collection (like reduce).
I think that last point in #Lee's answer should be heavily emphasized.
Unless you absolutely need arrays for performance reasons, you should really be using vectors here. That entire chunk of code suddenly becomes trivial once you start using native Clojure structures:
; Create 10 0s, then put them in a vector
(vec (repeat 10 0))
You can even skip the call to vec if you're ok using a lazy sequence instead of a strict vector.
It should also be noted though that pre-initializing the elements to 0 is unnecessary. Unlike arrays, vectors are variable length; they can be added to and expanded after creation. It's much cleaner to just have an empty vector and add elements to it as needed.
You can create and modify arrays in clojure, your example would look like:
(defn example []
(let [arr (int-array 10)
n 10]
(aset arr 0 1)
(doseq [i (range (inc n))]
(aset arr i 0))
(aget arr n)))
Be aware that this example will throw an exception since array[i] is out of bounds when i = 10.
You will usually use vectors in preference to arrays since they are immutable.
You can get a good start here:
Brave Clojure
The Clojure CheatSheet

Arity of anonymous functions in Clojure [duplicate]

This question already has answers here:
How many arguments does an anonymous function expect in clojure?
(3 answers)
Closed 5 years ago.
I'm very new to Clojure and asking myself, how the arity of an anonymous function is defined/deducted.
Please consider the following poor-man count function:
(reduce #(+ 1 %1) 0 '(1 2 3 55))
Running it with clojure I'm getting the following error message:
ArityException Wrong number of args (2) passed to: user/eval1157/fn--1158 clojure.lang.AFn.throwArity (AFn.java:429)
However, it works fine with JavaScript-Clojure and returns 4 as desired (you can execute the command here).
Changing the command by exchanging %1->%2 to
(reduce #(+ 1 %2) 0 '(1 2 3 55))
would compile on both versions (but no longer work as count). In this case seemingly, it can be deduced from %2 that there are at least two arguments.
So which version of Clojure is right? Am I allowed to feed an arbitrary amount of arguments to an anonymous function defined via #(...) or only as many as mentioned inside of this function?
Should it be considered a bug in JavaScript-Clojure?
Edit: As have been explained in comments and in answer, that this is just the way how JavaScript works. There are differences to Java-Clojure, which are documented here, in particular:
There is currently no runtime enforcement of arity when calling a fn
The parameters in the resulting function is determined by the highest numbered used parameter. Thus by using %2 both become a 2 arity function, but since you only use %1 (or %) it becomes a one arity function in both versions of Clojure.
In JavaScript you can pass as many arguments as you'd like and even pass fewer than the parameter list. Variables without matching argument become undefined and arguments without defined parameters are simply not bound and available in the function. ClojureScript would have to add argument checking in each function in order to get the same behavior as in Clojure. It would be a bug if this is the specified behavior. Many transpiled languages does this.
The solution for your example is to not use the short version but rather fn:
(reduce (fn [a _] (+ 1 a)) 0 '(1 2 3 55))

Terminology for example of codata in Clojure

Imagine the following function to give an infinite lazy sequence of fibonacci in Clojure:
(def fib-seq
(concat
[0 1]
((fn rfib [a b]
(lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
user> (take 20 fib-seq)
(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181)
Assuming
We take the pithy definition of codata as being "Codata are types inhabited by values that may be infinite".
That this Clojure example doesn't use a static type system (from core.typed) and so any description of codata is a 'working definition'
My question is - What part of the function above is the 'codata'. Is it the anonymous function? Is it the lazy sequence?
Codata is the dual of data. You work with data via structural induction which means that data is always finite. You work with codata via coinduction which means codata is potentially infinite (but not always).
In any case, if you can't properly define a finite toString or equality then it'll be codata:
Can we define a toString for an infinite streams? No, we'd need an infinite string.
Can we always define extensional equality for two infinite streams? No, that'd take forever.
We can't do the above for streams because they're infinite. But even potentially infinite causes undecidability (i.e. we can't give a definite yes or no for equality or definitely give a string).
So an infinite stream is codata. I think your second question is more interesting, is the function codata?
Lispers say that code is data because features like S-expressions allow manipulating the program just like data. Clearly we have already have a string representation of Lisp (i.e. source code). We can also take a program and check if it's made up of equal S-expressions (i.e. compare the AST). Data!
But let's stop thinking about the symbols that represent our code and instead start thinking about the meaning of our programs. Take the following two functions:
(fn [a] (+ a a))
(fn [a] (* a 2))
They give the same results for all inputs. We shouldn't care that one uses * and the other uses +. It's not possible to compute if any two arbitrary functions are extensionally equal unless they only work on finite data (equality is then just comparing input-output tables). Numbers are infinite so that still doesn't solve our above example.
Now let's think about converting a function to a string. Let's say we had access to the source representation of functions at runtime.
(defn plus-two [a] (+ a 2))
(defn plus-four [a] (plus-two (plus-two a)))
(show-fn plus-four)
; "(plus-two (plus-two a))"
Now, referential transparency says we can take function calls and replace them with the function bodies, with the variables substituted and the program always gives the same result. Let's do that for plus-two:
(defn plus-four [a] (+ (+ a 2) 2))
(show-fn plus-four)
; "(+ (+ a 2) 2)"
Oh... The result is not the same. We broke referential transparency.
So we also can't define toString or equality for functions. It's because they're codata!
Here are some resources I found helpful for understanding codata better:
Data, Codata, and Their Implications for Equality, and Serialization
Codata and Comonads in Haskell
Data and Codata on A Neighborhood of Infinity
Some slides from University of Nottingham
My personal thought is the return value of the call to lazy-cons is the point at which the type of the thing in question could first be said to be infinate and thus that is the point that I see codata'nes starting.