Scheme: The object () is not applicable - scheme

It's a beginner question. However it's more than 2 hours that I'm trying to find out the error (I've also made searches) but without success.
(define a (lambda (l i) (
(cond ((null? l) l)
(else (cons (cons (car l) i) (a (cdr l) i))))
)))
The function a should pair the atom i with each item of l. For example:
(a '(1 2 3) 4) should return ((1 4) (2 4) (3 4))
However when I try to use invoke the function I get:
The object () is not applicable
What's the error in my function?
I am using mit-scheme --load a.lisp to load the file. Then I invoke the function a by typing in interactive mode.

The error, as usually happens in lisp languages, depends on the wrong use of the parentheses, in this case the extra parentheses that enclose the body of the function.
Remove it and the function should work:
(define a (lambda (l i)
(cond ((null? l) l)
(else (cons (cons (car l) i) (a (cdr l) i))))))
Rember that in lisp parentheses are not a way of enclosing expressions, but are an important part of the syntax: ((+ 2 3)) is completely different from (+ 2 3). The latter expression means: sum the value of the numbers 2 and 3 and return the result. The former means: sum the value of the numbers 2 and 3, get the result (the number 5), and call it as a function with zero parameters. This obviously will cause an error since 5 is not a function...

Related

Memv procedure in Scheme

(define memv2
(lambda (x l)
(cond
((null? l) #f)
((eqv? (car l) x)
cdr l)
(else
(memv2 x (cdr l))))
Studying for an exam - this code has been provided in my notes as a replication of the built in memv function in Scheme. I was wondering if someone could explain what the #f is doing in this situation. Is it exiting the loop?
(memv takes in an element and a list, and returns the list from the point of the element onward, for example: (memv 2 '(1 2 3 4 5)) would return (2 3 4 5))
The #f value is returned when the procedure finishes traversing the list, which means that the searched element was not found, thus ending the recursion.

SICP Exercise 2.04

Reading SICP I am now at exercise 2.04, which is a procedural representation of cons, car and cdr, given in the book as follows:
(define (cons x y)
(lambda (m)
(m x y)))
(define (car z)
(z
(lambda (p q)
(p))))
Note, that for running the code I use racket with the following preamble in my code:
#lang racket
(define (Mb-to-B n) (* n 1024 1024))
(define MAX-BYTES (Mb-to-B 64))
(custodian-limit-memory (current-custodian) MAX-BYTES)
I also tried #lang scheme to no avail.
Here is what I understand:
About cons
cons returns a function.
This function which will apply another function given as parameter to the two parameters x and y of cons.
This means by calling cons we retain the possibility to apply a function to the two parameters and are able to treat them as some unit.
About car
car now uses the fact, that we can apply a function to the unit of 2 values given to cons, by giving a function as a parameter to the function, which we get returned from cons.
It supplies that function with a lambda expression, which always returns the first of two given values.
Usage
At first I tried the following:
(car (cons 1 2))
(car (cons 2 3))
(car (cons (cons 1 1) (cons 2 2)))
(car (car (cons (cons 1 1) (cons 2 2))))
However, that leads to errors:
:racket -l errortrace -t exercise-2.04-procedural-representation-of-pairs.rkt
application: not a procedure;
expected a procedure that can be applied to arguments
given: 1
arguments...: [none]
errortrace...:
/home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt:24:6: (p)
/home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt:33:0: (car (cons 1 2))
context...:
/home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt: [running body]
I could not understand what was wrong with my code, so I looked up some usage examples in other people's solutions. One is on http://community.schemewiki.org/?sicp-ex-2.4:
(define x (cons 3 4))
(car x)
But to my surprise, it doesn't work! The solution in the wiki seems to be wrong. I get the following error:
application: not a procedure;
expected a procedure that can be applied to arguments
given: 3
arguments...: [none]
errortrace...:
/home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt:24:6: (p)
/home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt:42:0: (car x)
context...:
/home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt: [running body]
What am I doing wrong here?
You have an error in your code. Instead of:
(define (car z)
(z
(lambda (p q)
(p))))
you should have written (see the book):
(define (car z)
(z
(lambda (p q)
p)))
Note that in the last row p is written without parentheses.
The message: application: not a procedure means that p is not a procedure (it is actually a number), while with the notation (p) you are calling it as a parameterless procedure.

Product of squares of odd elements in list in Scheme

I wanted to write a code in Scheme that writes the square odd elements in list.For example (list 1 2 3 4 5) for this list it should write 225.For this purpose i write this code:
(define (square x)(* x x))
(define (product-of-square-of-odd-elements sequence)
(cond[(odd? (car sequence)) '() (product-of-square-of-odd-elements (cdr sequence))]
[else ((square (car sequence)) (product-of-square-of-odd-elements (cdr sequence)))]))
For run i write this (product-of-square-of-odd-elements (list 1 2 3 4 5))
and i get error like this:
car: contract violation
expected: pair?
given: '()
What should i do to make this code to run properly? Thank you for your answers.
First of all, you need to do proper formatting:
(define (square x) (* x x))
(define (product-of-square-of-odd-elements sequence)
(cond
[(odd? (car sequence))
'() (product-of-square-of-odd-elements (cdr sequence))]
[else
((square (car sequence)) (product-of-square-of-odd-elements (cdr sequence)))]))
Now there are multiple issues with your code:
You are trying to work recursively on a sequence, but you are missing a termination case: What happens when you pass '() - the empty sequence? This is the source of your error: You cannot access the first element of an empty sequence.
You need to build up your result somehow: Currently you're sending a '() into nirvana in the first branch of your cond and put a value into function call position in the second.
So let's start from scratch:
You process a sequence recursively, so you need to handle two cases:
(define (fn seq)
(if (null? seq)
;; termination case
;; recursive case
))
Let's take the recursive case first: You need to compute the square and multiply it with the rest of the squares (that you'll compute next).
(* (if (odd? (car seq)
(square (car seq))
1)
(fn (cdr seq)))
In the termination case you have no value to square. So you just use the unit value of multiplication: 1
This is not a good solution, as you can transform it into a tail recursive form and use higher order functions to abstract the recursion altogether. But I think that's enough for a start.
With transducers:
(define prod-square-odds
(let ((prod-square-odds
((compose (filtering odd?)
(mapping square)) *)))
(lambda (lst)
(foldl prod-square-odds 1 lst))))
(prod-square-odds '(1 2 3 4 5))
; ==> 225
It uses reusable transducers:
(define (mapping procedure)
(lambda (kons)
(lambda (e acc)
(kons (procedure e) acc))))
(define (filtering predicate?)
(lambda (kons)
(lambda (e acc)
(if (predicate? e)
(kons e acc)
acc))))
You can decompose the problem into, for example:
Skip the even elements
Square each element
take the product of the elements
With this, an implementation is naturally expressed using simpler functions (most of which exist in Scheme) as:
(define product-of-square-of-odd-elements (l)
(reduce * 1 (map square (skip-every-n 1 l))))
and then you implement a helper function or two, like skip-every-n.

Scheme - How do I return a function?

This function is displaying the correct thing, but how do I make the output of this function another function?
;;generate an Caesar Cipher single word encoders
;;INPUT:a number "n"
;;OUTPUT:a function, whose input=a word, output=encoded word
(define encode-n
(lambda (n);;"n" is the distance, eg. n=3: a->d,b->e,...z->c
(lambda (w);;"w" is the word to be encoded
(if (not (equal? (car w) '()))
(display (vtc (modulo (+ (ctv (car w)) n) 26)) ))
(if (not (equal? (cdr w) '()))
((encode-n n)(cdr w)) )
)))
You're already returning a function as output:
(define encode-n
(lambda (n)
(lambda (w) ; <- here, you're returning a function!
(if (not (equal? (car w) '()))
(display (vtc (modulo (+ (ctv (car w)) n) 26))))
(if (not (equal? (cdr w) '()))
((encode-n n)(cdr w))))))
Perhaps a simpler example will make things clearer. Let's define a procedure called adder that returns a function that adds a number n to whatever argument x is passed:
(define adder
(lambda (n)
(lambda (x)
(+ n x))))
The function adder receives a single parameter called n and returns a new lambda (an anonymous function), for example:
(define add-10 (adder 10))
In the above code we created a function called add-10 that, using adder, returns a new function which I named add-10, which in turn will add 10 to its parameter:
(add-10 32)
=> 42
We can obtain the same result without explicitly naming the returned function:
((adder 10) 32)
=> 42
There are other equivalent ways to write adder, maybe this syntax will be easier to understand:
(define (adder n)
(lambda (x)
(+ n x)))
Some interpreters allow an even shorter syntax that does exactly the same thing:
(define ((adder n) x)
(+ n x))
I just demonstrated examples of currying and partial application - two related but different concepts, make sure you understand them and don't let the syntax confound you.

Why doesn't this scheme program work as expected?

(define wadd (lambda (i L)
(if (null? L) 0
(+ i (car L)))
(set! i (+ i (car L)))
(set! L (cdr L))))
(wadd 9 '(1 2 3))
This returns nothing. I expect it to do (3 + (2 + (9 + 1)), which should equate to 15. Am I using set! the wrong way? Can I not call set! within an if condition?
I infer from your code that you intended to somehow traverse the list, but there's nothing in the wadd procedure that iterates over the list - no recursive call, no looping instruction, nothing: just a misused conditional and a couple of set!s that only get executed once. I won't try to fix the procedure in the question, is beyond repair - I'd rather show you the correct way to solve the problem. You want something along these lines:
(define wadd
(lambda (i L)
(let loop ((L L)
(acc i))
(if (null? L)
acc
(loop (cdr L) (+ (car L) acc))))))
When executed, the previous procedure will evaluate this expression: (wadd 9 '(1 2 3)) like this:
(+ 3 (+ 2 (+ 1 9))). Notice that, as pointed by #Maxwell, the above operation can be expressed more concisely using foldl:
(define wadd
(lambda (i L)
(foldl + i L)))
As a general rule, in Scheme you won't use assignments (the set! instruction) as frequently as you would in an imperative, C-like language - a functional-programming style is preferred, which relies heavily on recursion and operations that don't mutate state.
I think that if you fix your indentation, your problems will become more obvious.
The function set! returns <#void> (or something of similar nothingness). Your lambda wadd does the following things:
Check if L is null, and either evaluate to 0 or i + (car L), and then throw away the result.
Modify i and evaluate to nothing
Modify L and return nothing
If you put multiple statements in a lambda, they are wrapped in a begin statement explicitly:
(lambda () 1 2 3) => (lambda () (begin 1 2 3))
In a begin statement of multiple expressions in a sequence, the entire begin evaluates to the last statement's result:
(begin 1 2 3) => 3

Resources