can some one please explain why
(some #(= 3 %) (range))
returns true but
(some #(= 4/3 %) (range))
never returns?
(range) produces an infinite sequence, so it'll just keep looking until it finds a natural number which is equal to 4/3, which isn't terribly likely.
Related
I'm learning Scheme and I want to compare two variables, but I don't know which type will have each of them.
On this SO answer, tells when to use =, eqv?, equal? and eq?, but I haven't found what I'm looking for.
My problem is that, the variables could be:
List: '(1 2) or '((10) 2).
String: 'sunny.
Number: 2.
So I could be comparing a number with a list, or a list with a string.
I have this code:
(define contains?
(lambda (lst element)
(cond
[(null? lst) #f]
[(equal? (car lst) element) #t]
(else [(contains? (cdr lst) elements)]))))
Which operator could I use to compare two of these variables?
If you want to test them for equality, then equal? is your best bet, it's the most general equality predicate and as such it works on multiple data types, and does recursive comparisons for the cases of lists, vectors, etc.:
Two values are equal? if and only if they are eqv?, unless otherwise specified for a particular datatype.
Datatypes with further specification of equal? include strings, byte strings, pairs, mutable pairs, vectors, boxes, hash tables, and inspectable structures. In the last six cases, equality is recursively defined; if both v1 and v2 contain reference cycles, they are equal when the infinite unfoldings of the values would be equal.
Just to add to Oscars answer. There are type specific procedures like string=?, char=?, and = for numbers, but to compare on general there are 3:
eq? tests if two arguments are the same value, as in created at the same instant or pointer equal.
eqv? tests if two primitive/scalar/atomic values look the same when displayed
equal? tests if two values look the same
Also, what is #t for eq? is guaranteed to be #t for eqv? abd what is #t for eqv? is guaranteed to be #t for equal?.
I have read books that completely skip eqv? and just keep eq? and equal? as general comparison. A fair amount of procedures that compare stuff have 3 versions of the 3 methods of comparison across the board. Eg. member (equal?), memv (eqv?), memq (eq?).
About eq?: We are guaranteed that '(), #t, #f and the symbols, like 'test would evaluate to the same value each and every time so they are always pointer equal. Other values might be, like number between a billion, but you have no guarantee all implementations will do it. (eq? 10 10) ; ==> #f is correct according to the standard as well as (eq? '(a) '(a)) ; ==> #t. In fact the two examnples can have any result and it's OK for the report. Notice how I say you are guaranteed to be #t withe eqv? if eq? yuilds #t but not vice versa. If something is eqv? you still have no idea what eq? would be.
I implemented a member? function in clojure as follows:
(defn member? [item seq]
(cond (empty? seq) false
(= item (first seq)) true
:else (recur item (rest seq))))
Unfortunately this doesn't work with infinite lists. Does anybody know of a way to implement it in order to be able to get:
(member? 3 (range)) -> true
Your implementation behaves correctly for an infinite input sequence. It does not terminate until an element has been found because the (empty? seq) case never falls.
Consider searching for something in an infinite space. When is it a good time to say it isn't there? There is no reliable way to tell. Limit the space you are searching in, e. g.:
(member? 3 (take 10 (range)))
You can't. I mean, at all.
In order to make sure there is no certain element you need to traverse the entire collection. Then and only then you can guarantee it's not there.
In some cases, such as your example, input sequence is ascending, i. e. every element of your sequence is less than its successive element. You can leverage that and make your sequence finite using take-while:
(member? 3 # is 3 a member of
(take-while # a sequence of elements
#(<= % 3) # up to 3 inclusively
range)) # from range
For me, your code already works: (member? 3 (range)) returns true.
But what is the point of checking for the existence of a value in an infinite sequence? It will either return true or it will never return.
I'm lost in clojure ratio. I can't understand it. Why do the equality and inequality tests behave this way?
(= 3/2 1.5)
;; false
(>= 3/2 1.5)
;; true
(> 3/2 1.5)
;;false
(not= 3/2 1.5)
;; true
Use == for numerical comparisons where you want to know if two numbers represent the same number regardless of types:
user> (= 3/2 1.5)
false
user> (== 3/2 1.5)
true
Though keep in mind that == is only for numbers and throws if given something not a number.
user> (== :1 :1)
ClassCastException clojure.lang.Keyword cannot be cast to java.lang.Number clojure.lang.Numbers.equiv (Numbers.java:206)
Clojure tries hard to keep you away from floats as they're susceptible to rounding errors:
user=> (+ 0.1 0.2)
0.30000000000000004
user=>
So the real reason the comparison fails is that there's no accurate way to represent 1.5 internally, and the moment the Clojure parser consumes "1.5" information is potentially lost.
By using fractions, there's no loss of information, so the fraction form 3/2 can be freely passed around to other functions without fear of runaway rounding errors as was the case with the infamous Patriot missile bug.
Simply put, in Clojure ratio is a type. It does not try to convert it to double or float or anything of that sort. That-way you can preserve what the number actually represents without losing any precision.
Check-out Rich Hickey's talk called "Clojure for Java Programmers" in YouTube, He explains it better.
It's a fragment of a larger task, but I'm really struggling with this. Resources for scheme/lisp are a lot more limited than C, Java, and Python.
If I pass in a var list1 that contains a list of numbers, how can I tell whether the list is in monotonically increasing order or not?
If a list has less than two elements, then we'll say 'yes.'
If a list has two or more elements, then we'll say 'no' if the first is larger than the second, otherwise recurse on the tail of the list.
(define (monotonically-increasing? lst)
(apply < lst))
Or, if you want monotonically-non-decreasing:
(define (monotonically-non-decreasing? lst)
(apply <= lst))
Yes, it's really as simple as that. Totally O(n), and no manual recursion required.
Bonus: For good measure:
(define (sum lst)
(apply + lst))
:-P
If efficiency is not an issue, you can do this:
(equal? list1 (sort list1 <=))
That's an O(n log n) solution, because of the sorting. For an optimal solution, simply compare each element with the next one and test if the current element is less than or equal to the next one, being careful with the last element (which doesn't have a next element). That'll yield an O(n) solution.
This is the general idea of what needs to be done, written in a functional style. Still not the fastest way to write the solution, but at least it's O(n) and very short; you can use it as a basis for writing a simpler solution from scratch:
(define (increasing? lst)
(andmap <=
lst
(append (cdr lst) '(+inf.0))))
The above checks for each number in lst if it's less than or equal to the next number. The andmap procedure tests if the <= condition holds for all pairs of elements in two lists. The first list is the one passed as a parameter, the second list is the same list, but shifted one position to the right, with the positive infinite value added at the end to preserve the same size in both lists - it works for the last element because any number will be smaller than infinite. For example, with this list:
(increasing? '(1 2 3))
The above procedure call will check that (<= 1 2) and (<= 2 3) and (<= 3 +inf.0), because all conditions evaluate to #t the whole procedure returns #t. If just one of the conditions had failed, the whole procedure would have returned #f.
My recursive function multiplies the given area by 1.5 until it reaches 100,000. The output is supposed to be how many times it had to multiply by 1.5. I think I understand most of what I need to do, but I'm not sure what to put in my (if) statement.
(define area-multiplier
(lambda (area)
(if (< 100000 area)
0 ;what do I put here?
(+ 1 (area-multiplier (* area 1.5))))))
Think about this using an example. In this case, the relevant examples are
(area-multiplier 100000)
and
(area-multiplier 100001)
What should these produce?
What you have is fine, except that if you want 100000 to return 0, then change the < to <=. :-)