How do I get the least significant bit of a (whole) number in Scheme?
Is this a fairly easy thing todo?
Thanks,
If your Scheme implementation supports SRFI 60, you can simply use:
(logand n 1)
(bitwise-and is a synonym that some Scheme implementations prefer, so if you don't have logand, check for bitwise-and too.)
Otherwise, if you are willing to assume you're on a two's-complement system (all mainstream platforms are), you can also use odd? or even?:
(if (odd? n) 1 0)
Related
I have a system that generates decision trees and converts them into nested Common Lisp if statements with predicates that check if a variable value is >= or <= a given integer e.g.
(LAMBDA (V1 V2)
(IF (>= V1 2)
(IF (<= V1 3)
(IF (<= V2 3)
(IF (>= V2 2) 16 (IF (>= V2 1) 6 0))
(IF (<= V2 4) 10 0))
(IF (<= V1 4)
(IF (>= V2 1) (IF (<= V2 3) 6 0) 0)
0))
(IF (>= V1 1)
(IF (>= V2 2) (IF (<= V2 4) 10 0) 0)
0)))
I then use eval to compile the Lisp code, producing functions that run much faster than interpreting the original decision tree. This compilation step takes surprisingly long, though: a function with 5000 nested ifs takes over a minute to compile (in Clozure Common Lisp on a powerbook), even though generating the if statement took about 100 milliseconds. Why does such a simple structure take so long? Is there anything I can do to substantially speed it up, some declaration maybe? I'd greatly appreciate any pointers you can offer.
The actual portable function to compile functions is called COMPILE.
You can tell the Common Lisp compiler to invest less work via low optimize qualities for speed, space, debug and compilation-speed - whether this has any influence depends on the implementation.
The Clozure CL compiler is usually not the brightest one, but relatively fast. Generally I think the compiler maintainer might be able to give you more hints how to speed up compilation. Generally I would look for three
tell the compiler to do less work: no type inference, no code optimization, no generation of debug information, no space saving effort, ...
if it is necessary tell the compiler things which it would have to infer - like instead of type inference by the compiler, declare all the types during code generation. But that would mean that you actually need some advantage from type declarations like increased runtime safety or code optimizations.
the compiler itself may have speed penalties which may depend on the size of the source code. For example if that is quadratic, the compile time would increase by four if we double the code size. Only the compiler maintainers may know what to do in those cases - maybe they would need to implement more efficient data structures or similar....
The next option is to use a Lisp interpreter. They usually have very little definition time overhead - but the code usually runs much slower at runtime. In some problem domains it may be possible to follow a mixed approach: compile code which changes not very often and interpret code which changes often.
You could certainly (declare (optimize (compilation-speed 3))), and maybe reduce other qualities (see http://clhs.lisp.se/Body/d_optimi.htm#optimize).
However, I'd guess that the slow compilation is caused by the optimizations the compiler makes, so the result seems likely to be not so fast at execution time. But maybe not, you'd have to experiment.
I'd also think about what optimizations you could make yourself using your domain knowledge. Hints for that might also come from analyzing the output of disassemble on your generated functions.
Finally, maybe you can translate your decision trees into lookup tables, if the number of distinct values is not too big.
Arguments will be evaluated during a function call in Lisp. Is there any way besides macro to print the argument without evaluation?
Take an example in Common Lisp:
(defun foo (&rest forms)
(loop for i in forms collect i))
Call "foo" in REPL toplevel:
CL-USER> (foo (= 1 2) (< 2 3))
Got the result:
(NIL T)
Is there any way to get this result?:
((= 1 2) (< 2 3))
You can’t do that in either Scheme or Common Lisp without macros. Of course, it’s also pretty trivial with macros, so feel free to use them if they fit your use case.
That said, there’s a bit more to this question than you may have anticipated. You’re effectively asking for a feature that was present in older Lisps that has fallen out of fashion, known as fexprs. A fexpr is exactly what you describe: a function whose operands are passed to it without being evaluated.
Most modern dialects have done away with fexprs in favor of only using macros, and you can see this Stack Overflow question for more information on why. The gist is that fexprs are hard to optimize, difficult to reason about, and generally less powerful than macros, so they were deemed both redundant and actively harmful and were summarily removed.
Some modern Lisps still support fexprs or something like them, but those dialects are rare and uncommon in comparison to the relative giants that are Scheme and CL, which dominate the modern Lisp world. If you need this sort of thing, just use macros. Better yet, just quote the arguments so you don’t need any macros at all. You’ll be more explicit (and therefore much clearer), and you’ll get the same behavior.
Yes; you can get the result with an operator called quote, if you don't mind one more level of nesting:
(quote ((= 1 2) (< 2 3)))
-> ((1 2) (2 3))
quote isn't a macro; it is a special operator.
I have just started reading The Little schemer. I have some problem understanding some words.
In page 27 it says,
The Law of Eq?
The primitive eq? takes two arguments. Each must be a non-numeric atom."
And a footnote says: In practice, some numbers may be arguments of eq?
I am using racket-minimal as my scheme interpreter. It evaluates (eq? 10 10) to #t.
There are many similar type of problems in TOYS chapter.
What did the author mean by that must(marked as bold) and the footnote?
It's traditional to embed some primitive data types such as low integers and characters in the pointer itself making those datatypes eq? even when the data came to be in the source at different times / points in source. However, numbers can be any size so even if number upto a certain implementation dependent size at some point they will be to big for the pointer. When you try (eq? 10000000000 10000000000) it might be #f on 32 bits systems and #t in 64 bit systems while (eqv? 10000000000 10000000000) is #t in any system.
Scheme's true identity predicate is eqv?. Eq? is an optimized version that is allowed to report #f instead of #t when applied to numbers, characters, or procedures. Most Scheme implementations of eq? do the right thing on small exact numbers (called "fixnums"), characters, and procedures, but fall down on larger numbers or numbers of other types.
So saying "MUST" means that you get only partly predictable results if you apply eq? to a number; the footnote means that in some cases (and this typically includes 10) you will get away with it. For details on what various Schemes actually do with fixnums, see FixnumInfo at the R7RS development site.
I recently started reading through Paul Graham's On Lisp with a friend, and we realized that we have very different opinions of reduce: I think it expresses a certain kind of recursive form very clearly and concisely; he prefers to write out the recursion very explicitly.
I suspect we're each right in some context and wrong in another, but we don't know where the line is. When do you choose one form over the other, and what do you think about when making that choice?
To be clear about what I mean by reduce vs. explicit recursion, here's the same function implemented twice:
(defun my-remove-if (pred lst)
(fold (lambda (left right)
(if (funcall pred left)
right
(cons left right)))
lst :from-end t))
(defun my-remove-if (pred lst)
(if lst
(if (funcall pred (car lst))
(my-remove-if pred (cdr lst))
(cons (car lst) (my-remove-if pred (cdr lst))))
'()))
I'm afraid I started out a Schemer (now we're Racketeers?) so please let me know if I've botched the Common Lisp syntax. Hopefully the point will be clear even if the code is incorrect.
If you have a choice, you should always express your computational intent in the most abstract terms possible. This makes it easier for a reader to figure out your intentions, and it makes it easier for the compiler to optimize your code. In your example, when the compiler trivially knows you are doing a fold operation by virtue of you naming it, it also trivially knows that it could possibly parallelize the leaf operations. It would be much harder for a compiler to figure that out when you write extremely low level operations.
I'm going to take a slightly-subjective question and give a highly-subjective answer, since Ira already gave a perfectly pragmatic and logical one. :-)
I know writing things out explicitly is highly valued in some circles (the Python guys make it part of their "zen"), but even when I was writing Python I never understood it. I want to write at the highest level possible, all the time. When I want to write things out explicitly, I use assembly language. The point of using a computer (and a HLL) is to get it to do these things for me!
For your my-remove-if example, the reduce one looks fine to me (apart from the Scheme-isms like fold and lst :-)). I'm familiar with the concept of reduce, so all I need to understand it is figure out your f(x,y) -> z. For the explicit variant, I had to think it for a second: I have to figure out the loop myself. Recursion isn't the hardest concept out there, but I think it is harder than "a function of two arguments".
I also don't care for a whole line being repeated -- (my-remove-if pred (cdr lst)). I think I like Lisp in part because I'm absolutely ruthless at DRY, and Lisp allows me to be DRY on axes that other languages don't. (You could put in another LET at the top to avoid this, but then it's longer and more complex, which I think is another reason to prefer the reduction, though at this point I might just be rationalizing.)
I think maybe the contexts in which the Python guys, at least, dislike implicit functionality would be:
when no-one could be expected to guess the behavior (like frobnicate("hello, world", True) -- what does True mean?), or:
cases when it's reasonable for implicit behavior to change (like when the True argument gets moved, or removed, or replaced with something else, since there's no compile-time error in most dynamic languages)
But reduce in Lisp fails both of these criteria: it's a well-understood abstraction that everybody knows, and that isn't going to change, at least not on any timescale I care about.
Now, I absolutely believe there are some cases where it'd be easier for me to read an explicit function call, but I think you'd have to be pretty creative to come up with them. I can't think of any offhand, because reduce and mapcar and friends are really good abstractions.
In Common Lisp one prefers the higher-order functions for data structure traversal, filtering, and other related operations over recursion. That's also to see from many provided functions like REDUCE, REMOVE-IF, MAP and others.
Tail recursion is a) not supported by the standard, b) maybe invoked differently with different CL compilers and c) using tail recursion may have side effects on the generated machine code for surrounding code.
Often, for certain data structures, many of these above operations are implemented with LOOP or ITERATE and provided as higher-order function. There is a tendency to prefer new language extensions (like LOOP and ITERATE) for iterative code over using recursion for iteration.
(defun my-remove-if (pred list)
(loop for item in list
unless (funcall pred item)
collect item))
Here is also a version that uses the Common Lisp function REDUCE:
(defun my-remove-if (pred list)
(reduce (lambda (left right)
(if (funcall pred left)
right
(cons left right)))
list
:from-end t
:initial-value nil))
I'm fairly new to Scheme and am attempting to learn it on my own from scratch. I'm stuck on the syntax of this problem. I know that if I want to find out if a number is a power of 2, in C for instance, I would simply do:
return (x & (x - 1)) == 0;
which would return true or false. How would I be able to convert this into a couple simple lines in Scheme?
I'll give you a hint since you're trying to learn the language.
Scheme has a function called (bitwise-and ...) which is equivalent to the & operator in C (there is also (bitwise-xor ...), (bitwise-not ..), etc., which do the expected thing).
(Here is the documentation of the (bitwise-and ...) function)
Given that, would you be able to translate what you've written in your question into Scheme code?
N.B: For a problem like this, you really don't need to resort to bitwise operations when using Scheme. Realistically, you should be writing a (possibly probably tail) recursive function that will compute this for you.
You can do this using a built in bitwise operator.
(define (pow2? x)
(= (bitwise-and x (- x 1))
0))
Scheme also has biwise operators.
But if you really want to develop your scheme skills, you should write a function that decides if an integer is a power of 2 by recursively dividing it by 2 until you are left with either 2 or with an odd number. This would be very inefficient, but really cool nonetheless.