Message passing scheme - scheme

Can anyone briefly explain to me how message passing is implemented in scheme? I think I am little off on the whole concept of message passing.

Take a look at SICP.
http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-17.html#%_sec_2.4.1
http://www.michaelharrison.ws/weblog/?p=50

Message passing in the context of closures
The following example defines a closure implementing a simple calculator. The function make-calculator is similar to what object oriented languages call the constructor. The difference is: make-calculator returns a function, while constructors return object values. In object oriented languages object values are first class values. Scheme does not have such values. An object first class values provides the functionality to access object member variables and object methods. In Scheme this functionality has to be emulated by the definition of a dispatch function. make-calculator returns such a function. The body of make-calculator defines
two variables a and b (member variables)
two mutation functions set-a! and set-b! (accessors)
four evaluation functions addition, subtraction, multiplication and division (methods)
The above definitions are local to the closure make-calculator. In an object oriented language they are called private. The dispatch function makes the functions public and keeps the variables private. This works, because the dispatch function has access to the local scope of the make-calculator closure. The dispatch function accepts a message and returns the matching function. This exposes the local functions to the caller of the dispatch function.
(define (make-calculator)
(define a)
(define b)
(define (set-a! value)
(set! a value))
(define (set-b! value)
(set! b value))
(define (addition)
(+ a b))
(define (subtraction)
(- a b))
(define (multiplication)
(* a b))
(define (division)
(/ a b))
(lambda (message)
(case message
((set-a!) set-a!)
((set-b!) set-b!)
((addition) addition)
((subtraction) subtraction)
((multiplication) multiplication)
((division) division))))
First the constructor has to be called to create an "object". calc is the dispatch function, which accepts different messages, which are just symbols.
(define calc (make-calculator))
Sending a message means calling the dispatch function with a symbol argument. The following sends the message set-a! to calc, which returns the value of the local function set-a!. The name of the message and the name of the local function are the same in this case. This helps to avoid confusion, but it is not required.
(calc 'set-a!) ;; => #<procedure set-a!>
Because calc returns a function, an additional application is necessary to call the accessor. The following sets a to 3 and b to 5.
((calc 'set-a!) 3)
((calc 'set-b!) 5)
Now we can calculate:
((calc 'addition)) ;; => 8
((calc 'subtraction)) ;; => -2
((calc 'multiplication)) ;; => 15
((calc 'division)) ;; => 3/15
The code works this way in Chez Scheme.

Related

Dynamic function call in Racket class combined with apply

TL;DR
What I'm looking for is a combination of the functions send/apply and dynamic-send. So that it finds a method of an object based on a symbol and unpacks a list of arguments.
Background and more info
For a project I am sending some "commands" trough the network with Racket's tcp-connect. At the receivers end this command should execute a method from a class and pass along its parameters.
Consider the following received 'message':
(define message (list 'set-switch! '3 'on))
(define method-name (car msg)) ;'set-switch!
(define parameters (cdr msg)) ;(list '3 'on)
And the following class:
(define light%
(class object%
(super-new)
...
(define/public (set-switch! id mode)
(vector-set! switches id mode))))
The problem now is that when executing this statement
(dynamic-send light-class method-name parameters)
it perfectly finds the method set-switch! but it calls it with only one parameter (list '3 'on).
The Racket docs mention those three functions for classes:
(send obj-expr method-id arg) which just executes a method of an object
(send/apply obj-expr method-id arg-list-expr) which executes a method AND unpacks the argument list
(dynamic-send obj method-name v) which finds a method-name based on a symbol
What I think I need is something like (dynamic-send/apply obj method-name arg-list-expr) which combines the last two mentioned.
Note: I know that I could just simply accept lists as parameters and use car and cdr in the functions itself to get the right values. But that's not what I want.
dynamic-send is a function (also known as procedure; e.g., car, vector-set!, +), so you can use apply:
(apply dynamic-send light-class method-name parameters)
Or even simply:
(apply dynamic-send light-class message)
The reason why send has the send/apply variant is that send is a form (also known as syntax; e.g., let, define, if), so apply doesn't work and hence send/apply is separately provided.

Call to the next most specific method does not work

Consider the class account :
(defclass account ()
((name :initarg :name :reader name)
(balance :initarg :balance :initform 0.00 :accessor balance)
(interest-rate :allocation :class :initform 0.06
:reader interest-rate)))
For this class, we define a method withdraw :
(defmethod withdraw ((acct account) amt)
(if (< amt (balance acct))
(decf (balance acct) amt)
'insufficient-funds))
And, another class password-account , that is a subclass of account:
(defclass password-account (account)
((password :initarg :password :reader password )))
And, the method withdraw, for this class:
(defmethod withdraw ((acct password-account) amt pass)
(if (equal (password acct) pass)
(call-next-method acct amt )
'wrong-password))
But this gives an error :
The generic function
#<STANDARD-GENERIC-FUNCTION COMMON-LISP-USER::WITHDRAW (1)>
takes 2 required arguments; was asked to find a method with
specializers
(#<STANDARD-CLASS COMMON-LISP-USER::PASSWORD-ACCOUNT>
#1=#<SB-PCL:SYSTEM-CLASS COMMON-LISP:T> #1#)
[Condition of type SB-PCL::FIND-METHOD-LENGTH-MISMATCH]
See also:
Common Lisp Hyperspec, FIND-METHOD [:function]
Restarts:
0: [RETRY] Retry SLIME REPL evaluation request.
1: [*ABORT] Return to SLIME's top level.
2: [ABORT] abort thread (#<THREAD "repl-thread" RUNNING {1005308033}>)
Why is this happening? And what does
was asked to find a method with specializers
mean here?
Here, the primary withdraw function had two arguments acct and amt, so in order to call it from a more specific method, which uses 3 arguments instead of 2, we can provide call-next-method with the arguments of the less specific withdraw method. But this still isn't working.
Any help appreciated.
Congruent lambda lists for generic functions
Methods of a generic function need to have congruent lambda lists. The language standard describes what that means: Congruent Lambda-lists for all Methods of a Generic Function.
As you can see the first rule says:
Each lambda list must have the same number of required parameters.
Required parameters tell us which arguments always have to be provided. Generic functions additionally allow optional, keyword and rest arguments. But there is no dispatch over these. The dispatch only works over the required arguments and all of those.
Having the same number of required parameters makes dispatch easier and allows the compiler to check for function calls with the wrong number of arguments.
Optional parameters need to be congruent, too
Note also that all methods of a generic function need to have the same number of optional parameters. See the second rule in the standard.
Wording
a parameter is something like a named variable in a lambda list
an argument is provided in a call to a function
Examples:
(defun foo (a b) (list a b))
a and b are parameters for the function foo.
(foo (+ 2 3) (* 4 5))
5 and 20 are the two arguments for the call of the function foo.

re-internilizing a symbol from namespace-mapped-symbols

I'm not sure if the question title is appropriate but here is what I wonder:
From the repl, I wanted to get the list of bindings defined in the current module. After some searching this seemed like a good solution:
(define (racket-symbols-set)
(list->set (namespace-mapped-symbols (module->namespace 'racket))))
(define (namespace-symbols-set)
(list->set (namespace-mapped-symbols)))
(define (module-bindings)
(set->list (set-subtract
(namespace-symbols-set)
(racket-symbols-set))))
so, calling (module-bindings) returns a list of symbols. But if I try to call a symbol from that result, such as doing ((first (module-bindings))), I get a "application: not a procedure" error although the first symbol is a procedure.
How do I call the corresponding procedure of that symbol?
You can look up the value of a namespace variable using namespace-variable-value. And since your namespace-symbols-set just uses the current namespace, which is also the default namespace for namespace-variable-value, using it is very simple.
For example, to invoke the procedure associated with the first item in the list returned by your module-bindings procedure:
((namespace-variable-value (car (module-bindings))))
Alternatively, specify your preferred namespace as the fourth argument of the namespace-variable-value call.
You need to evaluate that symbol in order for it to return the corresponding procedure.
> (define (foo) 'bar)
> (eval 'foo)
#<procedure:foo>
> ((eval 'foo))
'bar
Hence in your case
((eval (car (module-bindings))))
will call the first procedure of the list returned by module-bindings.

How to extract list from Scheme program?

I have been giving a language in Scheme.
(define-datatype statement statement?
(add1 (V symbol?))
(sub1 (V symbol?))
(skip (V symbol?))
(if-goto (V symbol?)
(l symbol?)))
(define-datatype instruction instruction?
(labeled (l symbol?)
(i statement?))
(unlabeled (i statement?)))
(define-datatype program program?
(a-program (l (list-of instruction?))))
I am trying to create a new function which will be able to convert the program into a list of instructions. How would I go about doing this?
Here is what I have so far:
(define pgm->list
(lambda (pgm)
;what goes here
sorry if this is wrong, if it is could you share a working implementation of your code?
i am really confused with
(define-datatype program program?
(a-program (l (list-of instruction?))))
what is list-of? i should imagine here that you want to declare some variants of programs.
a-program would be defined as a list of instructions... ok. if list-of returns a lambda that is a correct predicate (that returns true only when acted on a list of instructions) then
does this work?
(define pgm->list
(lambda (pgm)
(cases program pgm
(a-program (l) l))))
Edit : Since define-datatype was unknown to most of us except OP, i'm adding some documentation:
[syntax] (define-datatype TYPENAME [PREDICATE] VARIANT ...)
Defines a record type named TYPENAME, where VARIANT ... defines one or more
constructors for instances of this type. VARIANT should be of the form
VARIANT = (CONSTRUCTOR (FIELDNAME FIELDPRED) ...)
CONSTRUCTOR is the name of a constructor procedure that will be defined with as
many arguments as fields are specified. (FIELDNAME FIELDPRED) ... specify the name
for each field and a procedure of one argment that should return a true value for
legal field values.
The optional PREDICATE should be the name of a procedure that will be defined and
which returns #t when applied to an instance of this variant record.
[syntax] (cases TYPENAME EXP CLAUSE ...)
A facility for matching and deconstructing the instance EXP of the variant record
with the name TYPENAME. Each CLAUSE specifies a constructor with field-names and
a body to execute when the constructor matches the record instance:
CLAUSE = (CONSTRUCTOR (FIELDNAME ...) BODY ...)
| (else BODY ...)
cheers!

Filter type String in Clojure

Currently I'm trying to learn Clojure and I would like to write a function that has a variable amount of parameters. This function should filter every input to check if it's a string or not. If it does, every input of type string should be returned..
Clojure is hard for me and different way of thinking, but am I on the right direction here.. I can't seem to solve it:
(defn returnString [& y]
(if (next y)
(filter (fn [x] (= (type x) "java.lang.String"))y)
(recur (next x))))
Thanks!
There is a function called string? that returns true if the argument is a string, or false if not.
=> (string? "hi")
true
=> (string? 100)
false
=> (string? ["a" "b" "c"])
false
So with that in mind, your function would look like:
(defn return-strings [& vals]
(filter string? vals))
The filter function will return a sequence (essentially a collection) of values, so there is no need worry about recursion (that is, using recur) in your custom function for this case.
The anonymous function you use to determine what is a string is very close to being correct. If you take a look at the source for string? by entering (source string?) into your REPL, you'll see:
(fn [x] (instance? String x))
Although, the approach you are taking would work as well. You just need to specify the String class instead of the string value you were giving. (Note, you can leave off java.lang because that package is automatically included just like it is in Java.)
(fn [x] (= (type x) String))

Resources