I am starting to learn Scheme and well, I am trying to implement my own max function that gives the max of just two parameters.
I've written the function like this:
(define (myMax x y) (cond ((> x y) (x)) ((< x y) (y))))
But every time I try calling it (myMax 100 40)(example) I get an error that says:
The object 100 is not applicable.
Searching the documentation of GNU's MIT-Scheme, they say:
This type indicates an error in which a program attempted to apply an object that is not a procedure. The object being applied is saved in the datum field, and the arguments being passed to the object are saved as a list in the operands field.
But what is that supposed to mean?
Weird thing is, I implemented a very simple function that adds two numbers and it works just fine, also an absolute value function that works fine; could it be the conditional is messed up?
Thanks
In Scheme (function-name arguments) is the syntax for applying a function to the given arguments. So (x) means "apply the function x to no arguments". However x is not a function, which the compiler is trying to tell you by saying that it's not "applicable".
Since you don't actually want to apply x, simply remove the parentheses around it. Same for (y) in the other case of the cond.
Related
This is what I want to happen:
[m | m<-[1..1000], k<-[3,5], m `mod` k == 0]
When I put that code in the console I get the result I want but when I try to turn it into a generalized function Haskell is just spitting out tons of errors and I cannot figure out how to make it work.
This is what I have:
multiplesOfKLessThanN :: Num a => [a] -> a -> [a]
multiplesOfKLessThanN ks n = [m | m<-[1..n], k<-ks, m `mod` k == 0]
problem1 = putStrLn(show(multiplesOfKLessThanN([3,5] 1000)))
main = problem1
One Such Error I am getting:
Couldn't match expected type 'Integer -> [a0]' with actual type '[Integer]'
I also get other errors but inconsistently. This is something I have noticed with Haskell, it likes to change error messages even when the code hasn't changed at all like wtf?
Your use of mutliplesOfKLessThanN is not correct
mutliplesOfKLessThanN([3,5] 1000)
Is not interpreted by Haskell as
Apply mutliplesOfKLessThanN with [3,5] and 1000.
but instead it is interpteted as
Apply [3,5] to 1000 and apply multiplesOfKLessThanN to the result.
I think your misconception is in how function application occurs. In many languages function application requires parentheses e.g. f(x). For Haskell parentheses only ever mean "do this operation first", and function application is achieved by putting things next to each other. So f(x) works in Haskell because it is the same as f x, but f(x y) is the same as f(x(y)) and tells Haskell to evaluate x y first and then give it to f.
With your code Haskell can't apply [3,5] as a function, which is what Haskell is telling you, it expected a function (in fact a specific type of function).
The proper way to write this would be
multiplesOfKLessThanN [3,5] 1000
This should handle that main error you are getting.
So the error here is a type error because you are trying to make a more general type a be used by the function modulo. If you look at the type mod it expects an integral type class changing your constraint from Num to Integral should resolve your issue
I'm trying to implement higher level functions in my Racket code, specifically with regards to this function:
(define (indivisible e L)
(map (remove 0 ((map ((lambda (x y) (modulo x y))) L e)))))
Essentially, I'm trying to remove all the elements that are divisible by e from the list. However, it keeps giving me an error that says that "the expected number of arguments did not match the given number (0 vs 2)". Why is this so?
Several places you have two sets of parentheses. Unless the parentheses are a part of a special form or macro, eg. let, it represent an application. Ie.
((lambda (x y) (modulo x y)))
Here the form (lambda ...) is evaluated and become a function. The second set of parentheses calls this function with no arguments. Since you have two arguments, x and y and not supplying any in your application it signals an error.
Another place where you do the same is around (map ....). Since I know map always evaluates to a list or null it looks kind of strange that you call it as a function ((map ...)).
If you are more familiar with algol languages like python, what you are doing is like someFunc(arg1 args2)() where you clearly see someFunc needs to return a function wince it's immediately called afterwards. The same in Scheme looks like ((some-func arg1 arg2)).
remove removes the first argument from the second argument list. It does not return a function so the outer map won't work.
To solve this I think you are looking for filter. You only need to make a predicate that is #f for the elements you don't want and you're done.
This is from the SICP book that I am sure many of you are familiar with. This is an early example in the book, but I feel an extremely important concept that I am just not able to get my head around yet. Here it is:
(define (cons x y)
(define (dispatch m)
(cond ((= m 0) x)
((= m 1) y)
(else (error "Argument not 0 or 1 - CONS" m))))
dispatch)
(define (car z) (z 0))
(define (cdr z) (z 1))
So here I understand that car and cdr are being defined within the scope of cons, and I get that they map some argument z to 1 and 0 respectively (argument z being some cons). But say I call (cons 3 4)...how are the arguments 3 and 4 evaluated, when we immediately go into this inner-procedure dispatch which takes some argument m that we have not specified yet? And, maybe more importantly, what is the point of returning 'dispatch? I don't really get that part at all. Any help is appreciated, thanks!
This is one of the weirder (and possibly one of the more wonderful) examples of exploiting first-class functions in Scheme. Something similar is also in the Little Schemer, which is where I first saw it, and I remember scratching my head for days over it. Let me see if I can explain it in a way that makes sense, but I apologize if it's not clear.
I assume you understand the primitives cons, car, and cdr as they are implemented in Scheme already, but just to remind you: cons constructs a pair, car selects the first component of the pair and returns it, and cdr selects the second component and returns it. Here's a simple example of using these functions:
> (cons 1 2)
(1 . 2)
> (car (cons 1 2))
1
> (cdr (cons 1 2))
2
The version of cons, car, and cdr that you've pasted should behave exactly the same way. I'll try to show you how.
First of all, car and cdr are not defined within the scope of cons. In your snippet of code, all three (cons, car, and cdr) are defined at the top-level. The function dispatch is the only one that is defined inside cons.
The function cons takes two arguments and returns a function of one argument. What's important about this is that those two arguments are visible to the inner function dispatch, which is what is being returned. I'll get to that in a moment.
As I said in my reminder, cons constructs a pair. This version of cons should do the same thing, but instead it's returning a function! That's ok, we don't really care how the pair is implemented or laid out in memory, so long as we can get at the first and second components.
So with this new function-based pair, we need to be able to call car and pass the pair as an argument, and get the first component. In the definition of car, this argument is called z. If you were to execute the same REPL session I had above with these new cons ,car, and cdr functions, the argument z in car will be bound to the function-based pair, which is what cons returns, which is dispatch. It's confusing, but just think it through carefully and you'll see.
Based on the implementation of car, it appears to be that it take a function of one argument, and applies it to the number 0. So it's applying dispatch to 0, and as you can see from the definition of dispatch, that's what we want. The cond inside there compares m with 0 and 1 and returns either x or y. In this case, it returns x, which is the first argument to cons, in other words the first component of the pair! So car selects the first component, just as the normal primitive does in Scheme.
If you follow this same logic for cdr, you'll see that it behaves almost the same way, but returns the second argument to cons, y, which is the second component of the pair.
There are a couple of things that might help you understand this better. One is to go back to the description of the substitution model of evaluation in Chapter 1. If you carefully and meticulously follow that substitution model for some very simple example of using these functions, you'll see that they work.
Another way, which is less tedious, is to try playing with the dispatch function directly at the REPL. Below, the variable p is defined to refer to the dispatch function returned by cons.
> (define p (cons 1 2))
#<function> ;; what the REPL prints here will be implementation specific
> (p 0)
1
> (p 1)
2
The code in the question shows how to redefine the primitive procedure cons that creates a cons-cell (a pair of two elements: the car and the cdr), using only closures and message-dispatching.
The dispatch procedure acts as a selector for the arguments passed to cons: x and y. If the message 0 is received, then the first argument of cons is returned (the car of the cell). Likewise, if 1 is received, then the second argument of cons is returned (the cdr of the cell). Both arguments are stored inside the closure defined implicitly for the dispatch procedure, a closure that captures x and y and is returned as the product of invoking this procedural implementation of cons.
The next redefinitions of car and cdr build on this: car is implemented as a procedure that passes 0 to a closure as returned in the above definition, and cdr is implemented as a procedure that passes 1 to the closure, in each case ultimately returning the original value that was passed as x and y respectively.
The really nice part of this example is that it shows that the cons-cell, the most basic unit of data in a Lisp system can be defined as a procedure, therefore blurring the distinction between data and procedure.
This is the "closure/object isomorphism", basically.
The outer function (cons) is a class constructor. It returns an object, which is a function of one argument, where the argument is equivalent to the name of a method. In this case, the methods are getters, so they evaluate to values. You could just as easily have stored more procedures in the object returned by the constructor.
In this case, numbers where chosen as method names and sugary procedures defined outside the object itself. You could have used symbols:
(define (cons x y)
(lambda (method)
(cond ((eq? method 'car) x)
((eq? method 'cdr) y)
(else (error "unknown method")))))
In which case what you have more closely resembles OO:
# (define p (cons 1 2))
# (p 'car)
1
# (p 'cdr)
2
I am trying to write a program in Common Lisp using GNU ClISP to compile it. I would like to enter a list such as (A(B (C) ()) (D (E) (F (G) ()))) and depending on the first word print out the pre-, in-, or post-order traversal. Example:
(pre '(A(B (C)... etc))
I am having trouble putting my logic into Clisp notation. I currently have the following code:
(defun leftchild (L)(cadr L))
(defun rightchild (L)(caddr L))
(defun data (L)(car L))
(defun pre (L)(if (null L) '()((data L)(pre(leftchild L))(pre(rightchild L)))))
... similar in and post functions
I get compiling errors saying that I should use a lambda in my pre function. I think this is due to the double (( infront of data because it is expecting a command, but I am not sure what I should put there. I don't think cond would work, because that would hinder the recursive loop. Also, will data L print as it is now? The compiler did not recognize (print (data L)).
I have been working on this code for over a week now, trying to troubleshoot it myself, but I am at a loss. I would greatly appreciate it if someone could explain what I am doing incorrectly.
Another question that I have is how can I make the program prompt a line to the user to enter the (pre '(A... etc)) so that when I run the compiled file the program will run instead of giving a funcall error?
Thank you for your time.
Short answer: If you want to use if, note that you'll need a progn in order to have more than one form in the consequent and alternative cases.
Long answer – also explains how to traverse accumulating the visited nodes in a list:
I guess this is homework, so I won't give you a full solution, but your question shows that you have basically the right idea, so I'll show you an easy, idiomatic way to do this.
First, you're right: The car of an unquoted form should be a function, so basically anything like (foo ...), where foo is not a function (or macro, special form ...), and the whole thing is to be evaluated, will be an error. Note that this does not hold inside special forms and macros (like cond, for example). These can change the evaluation rules, and not everything that looks like (foo bar) has to be a form that is to be evaluated by the normal evaluation rules. The easiest example would be quote, which simply returns its argument unevaluated, so (quote (foo bar)) will not be an error.
Now, about your problem:
An easy solution would be to have an accumulator and a recursive helper function that traverses the tree, and pushes the values in the accumulator. Something like this:
(defun pre (node)
(let ((result (list)))
(labels ((rec (node)
(cond (...
...
...))))
(rec node)
(nreverse result))))
The labels just introduces a local helper function, which will do the actual recursion, and the outer let gives you an accumulator to collect the node values. This solution will return the result as a list. If you just want to print each nodes value, you don't need the accumulator or the helper function. Just print instead of pushing, and make the helper your toplevel function.
Remember, that you'll need a base case where the recursion stops. You should check for that in the cond. Then, you'll need the recursive steps for each subtree and you'll need to push the node's value to the results. The order in which you do these steps decides whether you're doing pre-, in-, or post-order traversal. Your code shows that you already understand this principle, so you'll just have to make it work in Lisp-code. You can use push to push values to result, and consp to check whether a node is a non-empty list. Since there's nothing to do for empty lists, you'll basically only need one test in the cond, but you can also explicitly check whether the node is null, as you did in your code.
Nested lists in Common Lisp really confused me. Here is the problem:
By using recursion, let (nested-list 'b '(a (b c) d)) return t
if the first argument appears in the second argument (which could be
a nested list), and nil otherwise.
I tried find, but it only works if the first argument is '(b c).
I turned my eyes on lambda expressions. I want to flatten the second
argument first, and then use eq to compare the arguments.
(defun nested-list (x y)
(cond
((null y) ())
(t (append (lambda (flatten) (first y))
Then I got stuck. Even though I read a lot of stuff about lambda
expessions, it still confused me. I do not know how to recall it when
I need, I knew the funcall function, but you know I just cannot get
it. I just learnt Common Lisp for 5 days, so I hope you can give me a
hint. Thanks a lot!
First of all unless you mistyped if instead of iff the problem is quite trivial, just return t and you're done :-)
Seriously speaking instead when you need to solve a problem using recursion the idea often is simply:
if we're in a trivial case just return the answer
otherwise the answer is the same answer we'd get by solving a problem that it's just a little bit simpler that this, and we call ourself to solve this simplified version.
In the specific consider:
If the second argument is an empty list the answer is NIL
If the first argument is equal to the first element of the second argument then just return T instead
Otherwise if the first element of the second list is a list (therefore also possibly a nested list) and the element is contained in this multilist then return true (to check this case the function is calling itself)
Otherwise just check the same problem, but first dropping the first element of the second argument, because it has been checked (this also calls recursively the same function)
So basically 1 and 2 are the trivial cases; 3 and 4 are the cases in which you solve a simpler version of the problem.