First time stackoverflow user but occasional lurker, hope you guys can help me out.
So the first part of my assignment is to drop all ‘leading zeros’ in a list.
ex: (0 0 0 0 0 1 0 1 0 1) -> (1 0 1 0 1)
To do this, I thought to use an IF statement to check whether the first element was a 0 or not, and to recursively call the rest of the list until the there were no more leading zeros. As I have basically no idea how to program in Scheme, through searching the internet, I came up with what you see below. However when I run it, DrRacket tells me there are no arguments- I assume this either a syntactical error.. or more likely, I have no idea what I’m doing. So, if you could help me out, I’d really appreciate it!
>(define zz
> (lambda (n)
> (if (= (car (n)) 0)
> (zz (cdr (n)))
> ((n)))))
>
>(remove '(0 0 0 0 1 0 1 0))
The error I get in DrRacket is:
“procedure application: expected procedure, given: (0 0 0 0 1 0 1 0) (no arguments)”
Again, thanks a lot! (P.S. Sorry if the formatting is a little odd…)
EDIT
Okay, changing up some stuff, I now get a “expects type as 1st argument, given: (0 0 0 0 0 1 0 1 0); other arguments were: 0” error flagged at my if statement.
>(define zz
> (lambda n
> (if (= (car n) 0) <----- here
> (zz(cdr n))
> (n))))
EDIT 2
>(define zz
> (lambda (n)
> (if (= (car n) 0)
> (zz (cdr n))
> n)))
It works, thank you very much!
(num)is not correct – you’re trying to call42or whatever as a command. (Also, yourifsyntax is off; you may want to do read more code to get a better feel for the syntax).This should compile:
Parenthesis in Lisp are for calling functions, unless used in quotes.
Okay, the OP asked about a general rundown of the syntax for Scheme.
a– A symbol, which is looked up by the evaluator and substituted for its value. Some symbols (such as42) evaluate to themselves.'a– This “quotes” the symbol and transforms it into(quote a).quoteprevents its argument from being evaluated – instead, the valueais returned. Not the string “a”, not the result of looking upa,aitself. This also works for lists ('(1 2 3))(if <expr> <true-value> <false-value>)– This evaluates<expr>, and sees if its value is truthy or not, and executes the corresponding value.(cond (<expr> <true-value>)– This runs though its arguments, and evaluates the...
(else <false-value>))
carof it to see if it is true. If it is, the value of evaluating thecdris returned. Otherwise, it skips to the next value.(define <name> <expr>)– Sets the value of evaluating the second argument to the name of the first argument.(lambda <arg-list> <body>)– Creates a procedure which is the result of binding the arguments passed in to the names present in the second argument and evaluating the third argument.(<func> <arg1> <arg2> ... <argn>)– If the evaluator finds out that none of the above patterns match, then it calls thecarof the list as a function, with the arguments in thecdr.