Racket/Scheme converting "-0" to "-0.0" - scheme

I am writing a simple interpreter that should
output: +inf or -inf for the following computations:
(/ 0)
(/ 1 0)
(/ -0)
I notice that replaced 0 by 0.0 gives me the behavior I want.
But I haven't figured out to convert -0 to -0.0.
exact->inexact loses the negative sign.
(exact->inexact -0) gives 0.0.

To do this, with the literal text -0 you would have to change the Reader so that -0 reads equal to -0.0, an inexact version. To be consistent you might want to read every number as an inexact number, whether it has a decimal point or not.
It's worth noting that you can do this by prefixing a number #i, for example #i-0 reads equal to -0.0. However, it sounds like you might want to change the reader so that every number reads the same as if it had #i prefixed onto it including -0.
One of the easier ways to extend the reader is with a readtable. You can make a function that extends a readtable like this:
;; Readtable -> Readtable
(define (extend-readtable orig-rt)
;; Char InputPort Any Nat Nat Nat -> Any
(define (rt-proc char in src ln col pos)
....)
...
(make-readtable orig-rt
#f 'non-terminating-macro rt-proc
...))
To use this to define a #lang language, you need to put the reader implementation in your-language/lang/reader.rkt. Here that's inexact-number/lang/reader.rkt, where the inexact-number directory is installed as a single-collection package (raco pkg install path/to/inexact-number).
inexact-number/lang/reader.rkt
#lang racket
(provide (rename-out [-read read]
[-read-syntax read-syntax]
[-get-info get-info]))
(require syntax/readerr
syntax/module-reader)
;; Readtable -> Readtable
(define (extend-readtable orig-rt)
;; Char InputPort Any Nat Nat Nat -> Any
(define (rt-proc char in src ln col pos)
....)
...
(make-readtable orig-rt
#f 'non-terminating-macro rt-proc))
;; [X ... -> Y] -> [X ... -> Y]
(define ((wrap-reader rd) . args)
(parameterize ([current-readtable (extend-readtable (current-readtable))])
(apply rd args)))
(define-values [-read -read-syntax -get-info]
(make-meta-reader 'inexact-number
"language path"
lang-reader-module-paths
wrap-reader
wrap-reader
identity))
The main work goes into filling in the .... holes in the extend-readtable function. Within the rt-proc, you can have it "peek" into the input port in to see if its a number, and if it is, call the Racket reader on a port that has #i appended to the front of in. You might be able to do this with something like input-port-append:
(input-port-append #f (open-input-string "#i") in)
In the context of extend-readtable, here's some code that does the peeking and re-reading:
;; Readtable -> Readtable
(define (extend-readtable orig-rt)
;; Char InputPort Any Nat Nat Nat -> Any
(define (rt-proc char in src ln col pos)
(define try-in (peeking-input-port in))
(define try (read/recursive try-in char orig-rt))
(cond
[(number? try)
;; read it as if it had #i on the front
(define prefix (string-append "#i" (string char)))
(define inexact-in
(input-port-append #f (open-input-string prefix) in))
(read-syntax/recursive src inexact-in #f orig-rt)]
[else
;; read normally
(read-syntax/recursive src in char orig-rt)]))
(make-readtable orig-rt
#f 'non-terminating-macro rt-proc))
Once you have this done, you should be able to use it like this:
#lang inexact-number racket
-0
; => -0.0
(/ -0)
; => -inf.0
P.S. I have now made #lang inexact-number available on the Racket package server, as the package inexact-number-lang. By the way, there's also #lang exact-decimal, which has the opposite affect of making numbers like 5.2 into exact rational numbers.

This is because -0 in Racket is the same literal datum that can also be written as 0, +0, 0000000, #e0, #e-0/1, -00000/1, or in various other ways. All of these syntaxes produce the very same value from the reader, which is an exact integer. Unlike floating-point numbers, exact numbers don't have signed zeros. To illustrate:
> (exact-integer? 0)
#t
> (exact-integer? +0)
#t
> (exact-integer? -0)
#t
> (eq? +0 -0)
#t
> (eq? -0 0)
#t
To get the behavior you want, you need to adjust the reader layer so that 0 and -0 don't produce the same value. I don't think there is a built-in parameter for doing what you want (there are for many other reader customizations), but you can do it by creating a custom readtable.
I would need more context to give you further guidance (for example, you say you're writing an "interpreter," which isn't the usual way of making a DSL in Racket), but my first inclination would be that, rather than re-implementing number parsing, you might map - to a "non-terminating-macro" and handle the rest in the expander (or interpreter) layer.

-0 doesn't exist! If you enter something silly like (define x -0) and press the Macro stepper #'> before any transformations you'll see it has read it in as (define x 0). The sign is truncated by the reader since integers doesn't have positive and negative zero like IEEE754 does. Thus unless you create your own language with your own reader that can discriminate on signed zero mapped to a data structure that supports it you cannot solve this.
IEEE754 floating points has the sign as it's own bit and thus every number, including 0, can be both positive and negative.
As for Scheme standard: Before R6RS there was no requirement for a full numeric tower and the report even mentions that a floating point only Scheme might be useful. Thus I believe some implementations of R5RS actually might read -0 as -0.0.

Related

Emacs lisp, how to dynamically create quoted expression including special chars like `?1`?

I would like to dynamically create a list of chars to use with read-char-choice. From this answer of similar question, how to construct the list programmatically with unquoted values as choices, ?1 with a function. The function that I ended up is
(defun prompt-list (name-list)
"docstring"
(let ((names name-list)
(name-num 1)
(choice-list (list)))
(dolist (x names)
(add-to-list 'choice-list
`(,name-num ;; in that part how to create the ?1, ?2 but dynamically
,x (lambda () (setq project-headers x))))
(setq name-num (+ 1 name-num)))
choice-list))
when I try to run it it returns error : Format specifier doesn’t match argument type.
In my understanding it need a char type, so my question is how to produce char types programmatically?
?1 is the read syntax for the character '1', which has the integer value 49. You can use the read syntax to initialize your name-num variable, rather than using the integer 1:
(defun prompt-list (name-list)
"docstring"
(let ((names name-list)
(name-num ?1)
(choice-list (list)))
(dolist (x names)
(add-to-list 'choice-list `(,name-num
,x (lambda () (setq project-headers ',x)))
t)
(setq name-num (+ 1 name-num)))
choice-list))
A couple of things to note:
You want the use ,x when setting project-headers, not just x, as the latter won't be valid by the time the lambda is invoked.
You want to append to choice-list as you build it, which is what the final t argument to add-to-list above does, otherwise your read-char-choice prompt will be in reverse order.

case and quotation in scheme & racket

I was a bit surprised by this racket code printing nay when I expected yeah:
(define five 5)
(case 5
[(five) "yeah"]
[else "nay"])
Looking at the racket documentation for case makes it clearer:
The selected clause is the first one with a datum whose quoted form is equal? to the result of val-expr.
So it's about quotation. I'm pretty sure that I did not yet fully grasp what quotation in lisps can buy me. I understand it in the viewpoint of macros and AST transformation. However I'm confused why is it helpful in the case of case for instance..?
I'm also curious, with this specification of case, can I use it to achieve what I wanted to (compare the actual values, not the quoted value), or should I use another construct for that? (cond, while strictly more powerful, is more verbose for simple cases, since you must repeat the predicate at each condition).
The problem is that case introduces implicit quote forms, which cause your example to work for 'five (whose value is 'five), instead of five (whose value is 5).
I almost never use case because of exactly this problem. Instead I use racket's match form with the == pattern:
(define five 5)
(define (f x)
(match x
[(== five) "yeah"]
[_ "nay"]))
(f 5) ; "yeah"
(f 6) ; "nay"
This produces "yeah" on only the value 5, just like you expected. If you wanted it to return "yeah" when it's equal to either five or six, you can use an or pattern:
(define five 5)
(define six 6)
(define (f x)
(match x
[(or (== five) (== six)) "yeah"]
[_ "nay"]))
(f 5) ; "yeah"
(f 6) ; "yeah"
(f 7) ; "nay"
And if you really want to match against quoted datums, you can do that by writing an explicit quote form.
(define (f x)
(match x
[(or 'five 'six) "yeah"]
[_ "nay"]))
(f 5) ; "nay"
(f 6) ; "nay"
(f 7) ; "nay"
(f 'five) ; "yeah"
(f 'six) ; "yeah"
These quote forms are implicit and invisible when you use case, lurking there waiting to cause confusion.
The Racket documentation gives this grammar:
(case val-expr case-clause ...)
where
case-clause = [(datum ...) then-body ...+]
| [else then-body ...+]
Let's compare to your example:
(define five 5)
(case 5 ; (case val-expr
[(five) "yeah"] ; [(datum) then-body1]
[else "nay"]) ; [else then-body2])
We see that (five) is interpreted as (datum). This means that five is
a piece of data (here a symbol), not an expression (later to be evaluated).
Your example of case is evaluated like this:
First the expression 5 is evaluated. The result is the value 5.
Now we look at a clause at a time. The first clause is [(five) "yeah"].
Is the value 5 equal (in the sense of equal?) to one of the datums in (five)? No, so we look at the next clause: [else "nay"]. It is an else-clause so the expression "nay" is evaluated and the result is the value "nay".
The result of the case-expression is thus the value "nay".
Note 1: The left-hand sides of case-clauses are datums (think: they are implicitly quoted).
Note 2: The result of val-expr is compared to the clause datums using equal?. (This is in contrast to Scheme, which uses eqv?.
UPDATE
Why include case? Let's see how one can write the example using cond:
(define five 5)
(let ([val five])
(cond
[(member val '(five)) "yeah"]
[(member val '(six seven)) "yeah"] ; added
[else "nay"])
This shows that one could do without case and just use cond.
However - which version is easier to read?
For a case expression it is easy to see which datums the value is compared to.
Here one must look closely to find the datums. Also in the example we know beforehand that we are trying to find the value among a few list of datums. In general we need to examine a cond-expression more closely to see that's what's happening.
In short: having a case-expression increases readability of your code.
For the historically interested: https://groups.csail.mit.edu/mac/ftpdir/scheme-mail/HTML/rrrs-1986/msg00080.html disussed whether to use eqv? or equal? for case.
UPDATE 2
I'll attempt to given an answer to:
I'm still not clear on the quotation vs working simply on the values though.
I'm wondering specifically why doing the quotation, why working on datum instead
of working on values. Didn't get that bit yet.
Both approaches make sense.
Let's for the sake of argument look at the case where case uses expressions rather than datums in the left hand side of a clause. Also following the Scheme tradition, let's assume eqv? is used for the comparison. Let's call such a
case-expression for ecase (short for expression-case).
The grammar becomes:
(ecase val-expr ecase-clause ...)
where
ecase-clause = [(expr ...) then-body ...+]
| [else then-body ...+]
Your example now becomes:
(define five 5)
(ecase five
[('five) "yeah"]
[else "nay")
This doesn't look too bad and the result is what we are used to.
However consider this example:
(ecase '(3 4)
[('five (list 3 4) "yeah"]
[else "nay")
The result of this would be "nay". The two lists resulting from evaluating the expressions '(3 4) and (list 3 4) are not equal in the sense of eqv?.
This shows that if one chooses to use eqv? for comparisions, having expressions available on the left hand side won't be helpful. The only values that work with eqv? atomic values - and therefore one could just as well use implicit quotations and restrict the left hand side to datums.
Now if equal? was used it would make much more sense to use expressions on the left hand side. The original Racket version of case was the same as the one in Scheme (i.e. it used eq?) later on it was changed to used equal?. If case was designed from scratch, I think, expressions would be allowed rather than datums.
The only remaining issue: Why did the authors of Scheme choose eqv? over equal? for comparisons? My intuition is that the reason were performance (which back in the day was more important than now). The linked to post from the rrrs-authors mailing list gives two options. If you dig a little further you might be able to find responses.
I can't find a reference right now, but case statements use literal, unevaluated data in their different clauses because it is both a frequent use-case and more easily subject to efficient compilation.
You could probably write your own version of Clojure's condp macro or a custom conditional operator to handle your use case.

Generic functions allow different order of arguments

I defined a generic function taking 2 arguments:
(defgeneric interact (a b))
The order of the arguments should not be important, so (interact x y) and (interact y x) should be the same, but I don't want to define two methods that do the same for every combination of different objects.
A Method-Combination of this type should help:
(defmethod interact :around (a b)
(if (some-function a b)
;;some-function has to be true if (eq (class-of a) (class-of b))
;;else (some-function a b) is (not (some-function b a))
;;similar #'<=
(call-next method)
(interact b a))
But I would have to know #'some-function and be able to know the type of the arguments I have to define.
Edit: both proposed approaches have a few limitations discussed in the comments below. Please read them before using this answer!
Can I suggest two options - a working but hacky option for when you only have two arguments, and a vaguely sketched out generic approach which I think should work but I haven't written:
Option 1:
(defparameter *in-interact-generic-call* nil)
(defgeneric interact (x y))
(defmethod interact ((x T) (y T))
; this can be called on pretty much anything
(if *in-interact-generic-call*
(cause-some-kind-of-error) ; Replace this with a more sensible error call
(let ((*in-interact-generic-call* T))
(interact y x))))
(defmethod interact ((x integer) (y string))
; example
(print x )(prin1 y))
(interact 5 "hello") ; should print 5 "hello"
(interact "hello" 5) ; should print 5 "hello"
;(interact "hello" "hello") ; should cause an error
Essentially the idea is to define a generic function which always matches anything, use it to try to swap the arguments (to see if that matches anything better) and if it's already swapped the arguments then to raise some kind of error (I've not really done that right here).
Option 2
Define the generic function as something like interact-impl. Actually call the standard function (defined by defun) interact.
In interact, define a loop over all permutations of the order of your arguments. For each permutation try calling interact-impl (e.g. using (apply #'interact-impl current-permutation).)
At least in sbcl, no matching arguments gives me a simple-error. You probably would want to do a more detailed check that it's actually the right error. Thus the code in interact looks something like
; completely untested!
(do (all-permutations all-permutations (cdr all-permutations))
(...) ; some code to detect when all permutations are exhausted and raise an error
(let (current-permutation (first all-permutations))
(handler-case
(return (apply #'interact-impl current-permutation))
(simple-error () nil)) ; ignore and try the next option
)
)
So what you are looking for is an arbitrary linear order on the class objects.
How about string order on class names?
(defun class-less-p (a b)
"Lexicographic order on printable representation of class names."
(let* ((class-a (class-of a))
(name-a (symbol-name class-a))
(pack-a (package-name (symbol-package name-a)))
(class-b (class-of b))
(name-b (symbol-name class-b))
(pack-b (package-name (symbol-package name-b))))
(or (string< pack-a pack-b)
(and (string= pack-a pack-b)
(string<= name-a name-b)))))

Determine definition and parameter of a Scheme function in the interpreter? / How are functions stored in Scheme?

I want to create a function that can determine the definition of an arbitrary function in scheme. If we call such a function "definition", it would work as such:
(define (triple x) (* 3 x))
(definition triple) would return "(triple x) (* 3 x)".
There would be some implementation problems (such as with n-arity), but I'm concerned mostly with whether or not the definition of individual functions are easily retrievable in Scheme.
As a continuation, is there a way to create a function that can determine the parameters of an arbitrary function? Such that:
(parameters +) returns (number number) or something similar.
These questions both fall under the question of how functions are stored in Scheme - I found some sources which claimed that function definitions are stored with the function name, but I couldn't find out how exactly they were stored.
If this is impossible - is there a language where function definitions are easily retrievable?
There is nothing like that in Scheme. Individual implementations might have that, though.
In Common Lisp there is the standard function function-lambda-expression, which might be able to retrieve source code - depending on the implementation.
Example in LispWorks (reformatted to improve readability here):
CL-USER 65 > (defun triple (x) (* 3 x))
TRIPLE
CL-USER 66 > (function-lambda-expression #'triple)
(LAMBDA (X)
(DECLARE (SYSTEM::SOURCE-LEVEL #<EQ Hash Table{0} 42201D392B>))
(DECLARE (LAMBDA-NAME TRIPLE))
(* 3 X))
NIL
TRIPLE
SBCL:
* (defun triple (x) (* 3 x))
TRIPLE
* (function-lambda-expression #'triple)
(SB-INT:NAMED-LAMBDA TRIPLE
(X)
(BLOCK TRIPLE (* 3 X)))
NIL
TRIPLE
As you can see it returns three values: the code, whether it is a closure and the name of the function.

How do I Extract the First character of a symbol in scheme?

I want it to extract all the words that have a letter e in them.
eg.
(ewords '(i e ee o oo)) -> '(e ee)
Berkeley's 61a lecture uses (first 'word) to extract the first character of the word. However DrScheme screams at me when I try to do that. How do take the first character of the word? like
(first 'word)->'w.
You'll need to convert it to a string explicitly:
(first (symbol->string 'word)) -> "w"
(I'm not sure off the top of my head whether first operates on strings. You can use string->list to convert to a list and then take the first if it doesn't.)
EDIT: It might be easier to pass around strings instead of symbols in the first place -- to designate a string, use double quotes (e.g. (ewords '("i" "e" "ee" "o" "oo")).) I don't know if this is your intent, but since you're learning, I thought I should mention the distinction.
Symbols are primarily meant to be atomic values, i.e., they are not usually taken apart and examined. If you really want to do it you must first do some type conversions:
; #\a -> a
(define (char->symbol chr)
(string->symbol (list->string (list chr))))
; abc -> (a b c)
(define (symbol->list sym)
(map char->symbol
(string->list (symbol->string sym))))
You can now use first:
> (first (symbol->list 'word))
w
It depends, what is the data definition for a "word"?
Is it a sequence of characters (aka a string)? Is it a list of characters? A list of strings? A list of symbols?
Here is a function that meets your criteria, but as you can see, it is convoluted and I wonder if it is what you really want:
; symbol->list-of-symbols : symbol -> (ListOf symbol)
; To destructure a symbol into a list of its constituent parts
(define (symbol->list-of-symbols sym)
(map (lambda (s) (string->symbol (string s)))
(string->list (symbol->string sym))))

Resources