I am using Racket and Dr. Racket.
There is built-in function called andmap.
The built-in version of andmap works this way:
> (andmap positive? '(1 2 3))
#t
Function number usually works as:
(number? 3)
> #t
(number? '())
>#f
I do not get why this happens:
(andmap number? '())
> #t
I think the result should be false.
The documentation says:
*If the lsts are empty, then #t is returned.*
Why on earth would that make sense? I do not see it. I am curious about the design choices of languages, specially new ones, like Racket.
The reason (andmap pred '()) returns #t is exactly the same reason (and) returns #t… but that’s perhaps not the most useful explanation, is it? The real answer is that #t is the identity for logical AND, just like 0 is the additive identity and 1 is the multiplicative identity:
> (+)
0
> (*)
1
> (and)
#t
> (or)
#f
The idea here is that the identity will not change the output when combined with any given input. For example, just like (+ 0 x) is always x and (* 1 x) is always x, (and #t x) is always x and (or #f x) is always x. This is a useful property to have, since it cooperates well with the idiomatic way to sum a list in Scheme, (apply + lst):
> (apply + '(1 2 3))
6
> (apply + '())
0
Similarly, (apply * lst) can be used instead of a separate product function. The and and or operators cannot be used with apply, since they are short-circuiting and are thus implemented as macros instead of functions, but andmap and ormap implement that functionality instead.
If that argument doesn’t seem satisfying enough to you, you can also think about these things in their plain English definitions to come to the same conclusion. What does the andmap operation mean? Well, it asks a question: “Do all of the elements in this list satisfy a predicate?” On an empty list, the answer will always be yes, given that you cannot possibly produce a counterexample to that claim.
In contrast, ormap is the dual: “Does at least one of the elements in this list satisfy a predicate?” The answer will always be no, since it’s impossible to produce any element at all, so producing one that satisfies a predicate is surely impossible.
Related
I’m trying to get get my macro to do an extra evaluation of its result before returning it. Can this be done without eval?
I'm trying to solve the problem in exercise 4 below:
Define a macro nth-expr that takes an integer n and an arbitrary number of expressions, evaluates the nth expression and returns its value. This exercise is easy to solve, if you assume that the first argument is a literal integer.
4. As exercise 3, but assume that the first argument is an expression to be evaluated.
It's easy to get the macro to pick the right expression:
(defmacro nth-expr% (n &rest es)
`(nth ,n ',es))
CL-USER> (defvar i 1)
I
CL-USER> (nth-expr% (1+ i) (+ 2 3) (- 4 3) (+ 3 1))
(+ 3 1)
The expression (+ 3 1) is the one we want, but we want the macro to evaluate it to 4 before returning it.
It can of course be done with eval:
(defmacro nth-expr%% (n &rest es)
`(eval (nth ,n ',es)))
CL-USER> (nth-expr%% (1+ i) (+ 2 3) (- 4 3) (+ 3 1))
4
But is there another way?
It feels like the solution should be to put the body of nth-expr% in a helper macro and have the top level macro only contain an unquoted call to this helper:
(defmacro helper (n es)
`(nth ,n ',es))
(defmacro nth-expr (n &rest es) ; doesn't work!
(helper n es))
The idea is that the call to helper would return (+ 3 1), and this would then be the expansion of the call to nth-expr, which at run-time would evaluate to 4. It blows up, of course, because N and ES get treated like literals.
That's not that easy.
Using eval is not good, since eval does not evaluate the code in the local lexical environment.
Remember, if we allow an expression to be evaluated to determine the number of another expression to execute, then we don't know this number at macro expansion time - since the expression could be based on a value that needs to be computed - for example based on some variable:
(nth-expression
foo
(bar)
(baz))
So we might want to think about code which does that:
(case foo
(0 (bar))
(1 (baz)))
CASE is evaluating foo and then uses the result to find a clause which has the same value in its head. The consequent forms of that clause then will be evaluated.
Now we need to write code which expands the former into the latter.
This would be a very simple version:
(defmacro nth-expression (n-form &body expressions)
`(case ,n-form
,#(loop for e in expressions
and i from 0
collect `(,i ,e))))
Question: what might be drawbacks of using CASE like that?
Knuto: Rainer Joswig may be asking you to think about how the case statement works. Namely, that after evaluating the keyform (ie, the first argument), it will be compared sequentially to the key in each clause until a match is found. The comparisons could be time consuming if there are many clauses. You can discover this by carefully reading the entry for case in the Hyperspec (as he more than once has insisted I do):
The keyform or keyplace is evaluated to produce the test-key. Each of
the normal-clauses is then considered in turn.
Also note that constructing many case clauses will add to the time to expand and compile the macro at compile time.
Regarding your use of eval in nth-expr%%, you can still achieve the effect of an eval by switching to apply:
(defmacro nth-expr%% (n &rest es)
`(let ((ne (nth ,n ',es)))
(apply (car ne) (cdr ne))))
But see Plugging the Leaks at http://www.gigamonkeys.com/book/macros-defining-your-own.html about a more robust treatment.
In general, a more efficient way to process the expressions is as a simple vector, rather than a list. (The problem statement does not rule out a vector representation.) While nth and case involve searching through the expressions one-by-one, a function like aref or svref can directly index into it. Assuming a vector of expressions is passed to the macro along with an index, perhaps first requiring (coerce expressions 'simple-vector) if a list, then the result can be computed in constant time no matter how many expressions there are:
(defmacro nth-expr%%% (n es)
`(let ((ne (svref ',es ,n)))
(apply (car ne) (cdr ne))))
so that now
(defvar i 1)
(nth-expr%%% (1+ i) #((+ 2 3) (- 4 3) (+ 3 1))) -> 4
In racket, I'm aware of the member function which returns the first occurrence of an element if it exists or #f otherwise, but is there a function which just returns #t or #f for whether the element exists in a list?
The answer to this question is member. In Racket, everything that is not #f is true. Therefore, member works just fine for testing the presence of an element in a list:
> (if (member 3 '(1 2 3)) 'present 'absent)
'present
> (if (member 3 '(1 2)) 'present 'absent)
'absent
There’s no need to specifically produce #t upon success because everything in Racket that branches only cares about #f and non-#f values.
There are some rare situations in which you really do want a boolean value, such as if you are going to store the result in some data structure and don’t want to retain an unnecessary reference to the list. The usual idiom for doing this in Racket is (and v #t), where v is some value, since this is equivalent to writing (if v #t #f). Therefore, you could just surround your call to member with that:
> (and (member 3 '(1 2 3)) #t)
#t
Since this is so rarely necessary, this is more idiomatic in Racket than writing a separate member? function.
I don't think there's a standard function for this, but see true? and without-truthiness in the predicates library.
Defining true? is pretty easy:
(define (true? x)
(if x #t #f))
I'm a noob in scheme ... I am trying to make an exercise so that it will check if a number is a palindrome or not ( I know how to do it in c, c++ and java). But I keep getting this error "c: unbound identifier in module in: c". I searched wide and far for the error, and yes there are tens of topics on it, but all on complicated stuff that have nothing to do with my punny code. My question is, can somebody please explain to me what does the error actually mean and how can I avoid it ? My code so far :
#lang racket
(define (palindrome n)
(if (> 10 n) #t
(check n)
)
)
(define (check n)
(if (> n 0)
((= c (modulo n 10))
(= x (+ (* x 10) c))
(= n (/ n 10)))
(checkp )
)
)
(define (checkp k)
(if (= k n) #t
#f)
)
The error reported occurs in the check procedure. All those references to the variables called c and x will fail, what are those variables supposed to be? where do they come from? Remember: in Scheme = is used for comparing two numbers, not for assignment.
There are other problems. The last line of check is calling checkp, but you forgot to pass the parameter. Also the syntax in the if expression is wrong, you can't write more than two conditions in it (the "consequent" and the "alternative"), if you need more than two conditions you should use cond.
Please be careful with those parentheses, you must not use them to group expressions (they're not like curly braces!). In Scheme, if you surround an expression with () it means function application, and that's not what you want to do in check.
And in the checkp procedure we have the same problem: the variable n is unbound. It's just like in any other programming language: you have to make sure that the variables come from somewhere (a parameter, a local variable, a global definition, etc.), they can't simply appear out of thin air.
UPDATE
After the update, now it's clear what you wanted to do. I'm sorry to say this, but you don't have a good grasp of even the most basic concepts of the language. All along you needed to do an iteration (typically implemented via recursion), but this is reflected nowhere in your code - you'll have to grab a good book or tutorial on Sceheme, to get the basics right. This is how the code in Java or C would look like in Scheme:
(define (check k)
(let loop ((x 0) (n k))
(if (zero? n)
(= k x)
(loop (+ (* 10 x) (remainder n 10)) (quotient n 10)))))
(define (palindrome)
(display "Enter the number: ")
(if (check (read))
(display "The number is a palindrome")
(display "The number is not a palindrome")))
Use it like this:
(palindrome)
Enter the number: 12321
The number is a palindrome
It seems like in order to use multiple return values in Racket, I have to either use define-values or collect them into a list with (call-with-values (thunk (values-expr)) list). In the latter case, why would someone to choose to return multiple values instead of a list, if just have to collect them into a list anyway? Additionally, both of these are very wordy and awkward to work into most code. I feel like I must be misunderstanding something very basic about multiple-return-values. For that matter, how do I write a procedure accepting multiple return values?
Although I may be missing some of the Scheme history and other nuances, I'll give you my practical answer.
First, one rule of thumb is if you need to return more than 2 or 3 values, don't use multiple values and don't use a list. Use a struct. That will usually be easier to read and maintain.
Racket's match forms make it much easier to destructure a list return value -- as easy as define-values:
(define (f)
(list 1 2))
(match-define (list a b) (f))
(do-something-with a b)
;; or
(match (f)
[(list a b) (do-something-with a b)])
If you have some other function, g, that takes a (list/c a b), and you want to compose it with f, it's simpler if f returns a list. It's also simpler if both use a two-element struct. Whereas call-with-values is kind of an awkward hot mess, I think.
Allowing multiple return value is an elegant idea, because it makes return values symmetric with arguments. Using multiple values is also faster than lists or structs (in the current implementation of Racket, although it could work otherwise).
However when readability is a higher priority than performance, then in modern Racket it can be more practical to use a list or a struct, IMHO. Having said that I do use multiple values for one-off private helper functions.
Finally, there's a long, interesting discussion on the Racket mailing list.
Racket doc gives us the quintessential example why, in disguise:
> (let-values ([(q r) (quotient/remainder 10 3)])
(if (zero? r)
q
"3 does *not* divide 10 evenly"))
"3 does *not* divide 10 evenly"
We get two values directly, and use them separately in a computation that follows.
update: In Common Lisp, with its decidedly practical, down-to-the-metal, non-functional approach (where they concern themselves with each extra cons cell allocation), it makes much more sense, especially as it allows one to call such procedures in a "normal" way as well, automatically ignoring the "extra" results, kind of like
(let ([q (quotient/remainder 10 3)])
(list q))
But in Racket this is invalid code. So yeah, it looks like an extraneous feature, better to be avoided altogether.
Using list as the consumer defeats the purpose of multiple values so in that case you could just have used lists to begin with. Multiple values is actually a way of optimization.
Semanticly returning a list and several values are similar, but where you return many values in a list effort goes into creation of cons cells to make the list and destructuring accessors to get the values at the other end. In many cases however, you wouldn't notice the difference in performance.
With multiple values the values are on the stack and (call-with-values (lambda () ... (values x y z)) (lambda (x y z) ...) only checks the number to see if it's correct.. If it's ok you just apply the next procedure since the stack has it's arguments all set from the previous call.
You can make syntactic sugar around this and some popular ones are let-values and SRFI-8 receive is a slightly simpler one. Both uses call-with-values as primitive.
values is handy because it
checks that the number of elements returned is correct
destructures
For example, using
(define (out a b) (printf "a=~a b=~a\n" a b))
then
(let ((lst (list 1 2 3)))
(let ((a (first lst)) (b (second lst))) ; destructure
(out a b)))
will work even though lst has 3 elements, but
(let-values (((a b) (values 1 2 3)))
(out a b))
will not.
If you want the same control and destructuring with a list, you can however use match:
(let ((lst (list 1 2)))
(match lst ((list a b) (out a b))))
Note that he creation of the structure, e.g. (list 1 2) vs (values 1 2) is equivalent.
Should I use
(apply + (filter prime? (range 1 20)))
or
(reduce + (filter prime? (range 1 20)))
Edit: This is the source for prime in clojure from optimizing toolkit.
(defn prime? [n]
(cond
(or (= n 2) (= n 3)) true
(or (divisible? n 2) (< n 2)) false
:else
(let [sqrt-n (Math/sqrt n)]
(loop [i 3]
(cond
(divisible? n i) false
(< sqrt-n i) true
:else (recur (+ i 2)))))))
If you are asking in terms of performance, the reduce is better by a little:
(time (dotimes [_ 1e6] (apply + (filter even? (range 1 20)))))
"Elapsed time: 9059.251 msecs"
nil
(time (dotimes [_ 1e6] (reduce + (filter even? (range 1 20)))))
"Elapsed time: 8420.323 msecs"
nil
About 7% difference in this case, but YMMV depending on the machine.
You haven't provided your source for the prime? function, so I have substituted even? as the predicate. Keep in mind that your runtime may be dominated by prime?, in which case the choice between reduce and apply matters even less.
If you are asking which is more "lispy" then I would say that the reduce implementation is preferrable, as what you are doing is a reduce/fold in the functional programming sense.
I would think that reduce would be preferable when it is available, because apply uses the list as arguments to the function, but when you have a large number -- say, a million -- elements in the list, you will construct a function call with a million arguments! That might cause some problems with some implementations of Lisp.
(reduce op ...) is the norm and (apply op ...) the exception (notably for str and concat).
I would expect apply to realize a lazy list which could be ugly, and you never want to assume your list is not lazy, 'cause you could suddenly find yourself getting smacked with massive memory useage.
Reduce is going to grab them 1 by one and roll the results together into a single whole, never taking the whole list in at once.
i am going to play devil's advocate and argue for apply.
reduce is clojure's take on fold (more exactly foldl), the left-fold, and is usually defined with an initial element, because a fold operation has two parts:
an initial (or "zero") value
an operation for combining two values
so to find the sum of a set of numbers the natural way to use + is as (fold + 0 values) or, in clojure, (reduce + 0 values).
this explicitly shows the result for an empty list, which is important because it is not obvious to me that + returns 0 in this case - after all, + is a binary operator (all that fold needs or assumes).
now, in practice, it turns out that clojure's + is defined as more than a binary operator. it will take many or, even, zero values. cool. but if we're using this "extra" information it's friendly to signal that to the reader. (apply + values) does this - it says "i am using + in a strange way, as more than a binary operator". and that helps people (me, at least) understand the code.
[it's interesting to ask why apply feels clearer. and i think it's partly that you are saying to the reader: "look, + was designed to accept multiple values (that's what apply is used for), and so the language implementation will include the case of zero values." that implicit argument is not present with reduce applied to a single list.]
alternatively, (reduce + 0 values) is also fine. but (reduce + values) triggers an instinctive reaction in me: "huh, does + provide a zero?".
and if you disagree, then please, before you downvote or post a reply, are you sure about what (reduce * values) will return for an empty list?
I agree with Andrew Cooke. But I would like to add that since it already knows how to work and handle multiple arguments, we are essentially re-telling the '+' operator how to work by using it in the 'reduce', in my opinion.
Also, if I told you do to add a bunch of numbers together, you would probably use the '+' operator by itself, and not use 'reduce' at all.
(+ 1 2 3 etc...)
'apply' is just saying, I want to do the same thing, but use what's inside this list for the arguments. There is no extra reasoning required and you are using it as if the numbers didn't exist in a list to begin with, like you would if you were writing it out yourself.
(Reduce is so heavily used that using/reasoning about it in this case isn't a big deal at all, I think either way is fine, but personally prefer apply)