((lambda (proc) (proc "yes" "no")) (lambda (a b) a)) ;; yes
((lambda (a b) a) "yes" "no") ;; yes
My question is why are 1 and 2 has the same result and are they the same?
Can someone please elaborate it a bit clearly ?
They give the same result, but they're not "the same". They are two language constructs that happen to give the same result (well, yes, in a functional world, they are equivalent, but I don't think you're refering to that.)
Really, understanding the constructs goes down understanding the language itself (Scheme). I can give you a some hints.
Roughly speaking, the construction (X Y) means "function application". That is, the first X is a function and Y is a parameter, or a set of them. Then the function X is called with the Y parameter(s).
Take your second line, for example, you can see, decomposing it, that it has:
(<Function> "yes" "no")
that is, something that may be a function, then two parameters. In Scheme, you can build anonymous functions, that have no name, but that you specify what do they expect as parameters and what do they do when called. This is called a "lambda function". In your case, the lambda function is defined as:
(lambda (a b) a)
That is, a function without name that accepts two parameters a and b and returns the first one. If you put all together, you get
((lambda (a b) a) "yes" "no")
that clearly it is a function application that returns the first parameter passed, as the lambda function does that.
The first case is similar, but in this case, it is the function itself which is passed as an argument. You have:
(<Function> (lambda (a b) a))
where this Function accepts "something" that can be put to build an application expression and produce a result:
(lambda (proc) (proc "yes" "no"))
that is, accepts some function proc, and "calls" it with two parameters. Note that the function you pass, (lambda (a b) a) accepts two parameters and returns the first, so it produces "yes" again.
Related
I'm new with common-lisp and my stuck with this easy problem.
I need to define a function that return true if the input is an atom
So, if in enter in the command line atom 'a returns T, but my code not
Variable x has to be quoted or the result will be false.
(defun check (x)
if(atom 'x)
T)
There already is a function that does that. It is called atom:
(atom 1)
=> T
(atom '(1))
=> NIL
This is thus a rather pointless exercise. If you absolutely must, you could wrap it in another function call:
(defun pointless-exercise (x)
(atom x))
(pointless-exercise 1)
=> T
(pointless-exercise '(1))
=> NIL
Note that you absolutely must not quote that x in your function:
(defun failed-exercise (x)
(atom 'x))
-> WARNING: parameter x is unused
(failed-exercise 1)
=> T
(failed-exercise '(1))
=> T ; oops
That is because 'x means that the symbol x stands for itself and is not evaluated as a variable name, and a symbol is always an atom.
[This is an extended comment which is too long for one.]
Based on your comments either you are confused or your function cannot be written in Common Lisp.
Here's why:
you are writing a function, and so your function will obey the standard evaluation rules of the language for function applications;
you require your function, check to return t in a form (check a) where a is not previously known.
These two conditions can not be met. They can't be met because the evaluation rules for the language forbid it. In a form like (check a) the rules are:
find out what sort of thing check refers to;
if it refers to a function, evaluate all its arguments in left-to-right order in the current environment;
retrieve the function binding of check from the current environment (this step can happen before, after, or during (2));
apply it to the results of (2).
See 3.1.2.1.2.3 of the Hyperspec.
In your case this process fails at (2): a has no binding and so evaluation of a signals an error.
Given that you are being asked to write a function you must have misunderstood the question.
Further, it's unlikely that you were being asked merely to write a wrapper around atom: rather the chances are the question wanted you either to reimplement atom (hint: what is its definition?), or to implement some variant of atom which considers a different set of objects to be 'atomic' than atom does. Which of those is true we can't tell from your question as it stands (v1).
I'm trying to implement a prolog-like program using Racket. I'm very new to the language still. I was able to write the =or, =and, and == that are seen in the =parent function below, but I'm having trouble with query and I feel like it's a basic misunderstanding given my beginner's status with the language.
Here's the parent function:
(define (=parent x y)
(=or (=and (== x "Cronus") (== y "Zeus"))
(=and (== x "Zeus") (== y "Athena"))
(=and (== x "Athena") (== y "Erichthonius"))))
Here's the expected use:
(query (option) (=parent "Zeus" option))
...which will succeed when option is Athena.
I've given it a number of different attempts, but am always getting the wrong output and behavior. I initially tried to use the local-binding of let but I've simplified it even further and it still isn't working:
(define query
(lambda (arg1 arg2)
(for/list ([i (in-list arg1)])
(ormap (λ (x) arg2 x) i))))
I also took the approach of defining option as so:
(define (option)
(list '(Zeus Athena Erichthonius Cronus)))
Running the query code as shown above always results with an output of '(Zeus).
In the debugger, when I set a breakpoint at the for/list line, I see i => (Zeus Athena Erichthonius Cronus) and i never changes before query returns. I thought the code I wrote would iterate through the list, assigning i to each element, but that's not the case here. So where am I going wrong?
In addition, in each step through the debugger, I never enter the (=parent x y) function. And I'm not understanding why it isn't being called.
My last question: why can't I define option using a list of strings? (it produces: ormap: contract violation, expected: list? given: "Zeus"
(define (option)
(list "Zeus" "Athena" "Erichthonius" "Cronus"))
I'm at the early stages of designing a framework and am fooling around with typed/racket. Suppose I have the following types:
(define-type Calculate-with-one-number (-> Number Number))
(define-type Calculate-with-two-numbers (-> Number Number Number))
And I want to have a function that dispatches on type:
(: dispatcher (-> (U Calculate-with-one-number Calculate-with-two-numbers) Number))
(define (dispatcher f args)
(cond [(Calculate-with-one-number? f)
(do-something args)]
[(Calculate-with-two-numbers? f)
(do-something-else args)]
[else 42]))
How do I create the type-predicates Calculate-with-one-number? and Calculate-with-two-numbers? in Typed/Racket? For non-function predicates I can use define-predicate. But it's not clear how to implement predicates for function types.
Since I am self answering, I'm taking the liberty to clarify the gist of my question in light of the discussion of arity as a solution. The difference in arity was due to my not considering its implications when specifying the question.
The Problem
In #lang typed/racket as in many Lisps, functions, or more properly: procedures, are first class dataypes.
By default, #lang racket types procedures by arity and any additional specificity in argument types must be done by contract. In #lang typed/racket procedures are typed both by arity and by the types of their arguments and return values due to the language's "baked-in contracts".
Math as an example
The Typed Racket Guide provides an example using define-type to define a procedure type:
(define-type NN (-> Number Number))
This allows specifying a procedure more succinctly:
;; Takes two numbers, returns a number
(define-type 2NN (-> Number Number Number))
(: trigFunction1 2NN)
(define (trigFunction1 x s)
(* s (cos x)))
(: quadraticFunction1 2NN)
(define (quadraticFunction1 x b)
(let ((x1 x))
(+ b (* x1 x1))))
The Goal
In a domain like mathematics, it would be nice to work with more abstract procedure types because knowing that a function is cyclical between upper and lower bounds (like cos) versus having only one bound (e.g. our quadratic function) versus asymptotic (e.g. a hyperbolic function) provides for clearer reasoning about the problem domain. It would be nice to have access to abstractions something like:
(define-type Cyclic2NN (-> Number Number Number))
(define-type SingleBound2NN (-> Number Number Number))
(: trigFunction1 Cyclic2NN)
(define (trigFunction1 x s)
(* s (cos x)))
(: quadraticFunction1 SingleBound2NN)
(define (quadraticFunction1 x b)
(let ((x1 x))
(+ b (* x1 x1))))
(: playTone (-> Cyclic2NN))
(define (playTone waveform)
...)
(: rabbitsOnFarmGraph (-> SingleBound2NN)
(define (rabbitsOnFarmGraph populationSize)
...)
Alas, define-type does not deliver this level of granularity when it comes to procedures. Even moreover, the brief false hope that we might easily wring such type differentiation for procedures manually using define-predicate is dashed by:
Evaluates to a predicate for the type t, with the type (Any -> Boolean : t). t may not contain function types, or types that may refer to mutable data such as (Vectorof Integer).
Fundamentally, types have uses beyond static checking and contracts. As first class members of the language, we want to be able to dispatch our finer grained procedure types. Conceptually, what is needed are predicates along the lines of Cyclic2NN? and SingleBound2NN?. Having only arity for dispatch using case-lambda just isn't enough.
Guidance from Untyped Racket
Fortunately, Lisps are domain specific languages for writing Lisps once we peal back the curtain to reveal the wizard, and in the end we can get what we want. The key is to come at the issue the other way and ask "How canwe use the predicates typed/racket gives us for procedures?"
Structures are Racket's user defined data types and are the basis for extending it's type system. Structures are so powerful that even in the class based object system, "classes and objects are implemented in terms of structure types."
In #lang racket structures can be applied as procedures giving the #:property keyword using prop:procedure followed by a procedure for it's value. The documentation provides two examples:
The first example specifies a field of the structure to be applied as a procedure. Obviously, at least once it has been pointed out, that field must hold a value that evaluates to a procedure.
> ;; #lang racket
> (struct annotated-proc (base note)
#:property prop:procedure
(struct-field-index base))
> (define plus1 (annotated-proc
(lambda (x) (+ x 1))
"adds 1 to its argument"))
> (procedure? plus1)
#t
> (annotated-proc? plus1)
#t
> (plus1 10)
11
> (annotated-proc-note plus1)
"adds 1 to its argument"
In the second example an anonymous procedure [lambda] is provided directly as part of the property value. The lambda takes an operand in the first position which is resolved to the value of the structure being used as a procedure. This allows accessing any value stored in any field of the structure including those which evaluate to procedures.
> ;; #lang racket
> (struct greeter (name)
#:property prop:procedure
(lambda (self other)
(string-append
"Hi " other
", I'm " (greeter-name self))))
> (define joe-greet (greeter "Joe"))
> (greeter-name joe-greet)
"Joe"
> (joe-greet "Mary")
"Hi Mary, I'm Joe"
> (joe-greet "John")
"Hi John, I'm Joe
Applying it to typed/racket
Alas, neither syntax works with struct as implemented in typed/racket. The problem it seems is that the static type checker as currently implemented cannot both define the structure and resolve its signature as a procedure at the same time. The right information does not appear to be available at the right phase when using typed/racket's struct special form.
To get around this, typed/racket provides define-struct/exec which roughly corresponds to the second syntactic form from #lang racket less the keyword argument and property definition:
(define-struct/exec name-spec ([f : t] ...) [e : proc-t])
name-spec = name
| (name parent)
Like define-struct, but defines a procedural structure. The procdure e is used as the value for prop:procedure, and must have type proc-t.
Not only does it give us strongly typed procedural forms, it's a bit more elegant than the keyword syntax found in #lang racket. Example code to resolve the question as restated here in this answer is:
#lang typed/racket
(define-type 2NN (-> Number Number Number))
(define-struct/exec Cyclic2NN
((f : 2NN))
((lambda(self x s)
((Cyclic2NN-f self) x s))
: (-> Cyclic2NN Number Number Number)))
(define-struct/exec SingleBound2NN
((f : 2NN))
((lambda(self x s)
((SingleBound2NN-f self) x s))
: (-> SingleBound2NN Number Number Number)))
(define trigFunction1
(Cyclic2NN
(lambda(x s)
(* s (cos x)))))
(define quadraticFunction1
(SingleBound2NN
(lambda (x b)
(let ((x1 x))
(+ b (* x1 x1)))))
The defined procedures are strongly typed in the sense that:
> (SingleBound2NN? trigFunction1)
- : Boolean
#f
> (SingleBound2NN? quadraticFunction1)
- : Boolean
#t
All that remains is writing a macro to simplify specification.
In the general case, what you want is impossible due to how types are implemented in Racket. Racket has contracts, which are run-time wrappers that guard parts of a program from other parts. A function contract is a wrapper that treats the function as a black box - a contract of the form (-> number? number?) can wrap any function and the new wrapper function first checks that it receives one number? and then passes it to the wrapped function, then checks that the wrapped function returns a number?. This is all done dynamically, every single time the function is called. Typed Racket adds a notion of types that are statically checked, but since it can provide and require values to and from untyped modules, those values are guarded with contracts that represent their type.
In your function dispatcher, you accept a function f dynamically, at run time and then want to do something based on what kind of function you got. But functions are black boxes - contracts don't actually know anything about the functions they wrap, they just check that they behave properly. There's no way to tell if dispatcher was given a function of the form (-> number? number?) or a function of the form (-> string? string?). Since dispatcher can accept any possible function, the functions are black boxes with no information about what they accept or promise. dispatcher can only assume the function is correct with a contract and try to use it. This is also why define-type doesn't make a predicate automatically for function types - there's no way to prove a function has the type dynamically, you can only wrap it in a contract and assume it behaves.
The exception to this is arity information - all functions know how many arguments they accept. The procedure-arity function will give you this information. So while you can't dispatch on function types at run-time in general, you can dispatch on function arity. This is what case-lambda does - it makes a function that dispatches based on the number of arguments it receives:
(: dispatcher (case-> [-> Calculate-with-one-number Number Void]
[-> Calculate-with-two-numbers Number Number Void]))
(define dispatcher
(case-lambda
[([f : Calculate-with-one-number]
[arg : Number])
(do-something arg)]
[([f : Calculate-with-two-numbers]
[arg1 : Number]
[arg2 : Number])
(do-something-else arg1 arg2)]
[else 42]))
Trying my hand at Lisp. I wonder though, why does:
(defun hello(x)
(print x)
)
work fine, but:
(defun hello (x)
(print(x)) ; Fails with EVAL: undefined function X.
)
not?
In LISPs, non-empty, unquoted lists are considered (function, macro, or special form) calls.
So,
(print x)
is a function call to print with an argument x.
But,
(print (x))
is a function call to print with an argument equal to the value of (x). But since (x) is also non-empty list, in order to get the value of (x) there is an attempt to make a call to a non-existent function x with no arguments.
It's key to note that parentheses are not simply grouping syntax as they are in many other languages; they invoke function as well, similar to how X.val is not the same as X.val() in e.g. Python.
So in this case, you are trying to call x as though it were a function. But, depending on what you've passed to hello, x is not a function, and as such cannot be called.
I just start to learn Scheme today.
I wrote a function gcd(), but it always returns 0.
(define (gcd a b)
(cond (= b 0)
(a)
(else ((gcd b (modulo a b))))
)
)
Why I am wrong?
This should fix the problems:
(define (gcd a b)
(cond [(= b 0) a]
[else (gcd b (modulo a b))]))
You were incorrectly surrounding some expressions between parenthesis, and some parenthesis were missing from the cond expression.
Notice that in Scheme, when you surround something in parenthesis, say (a) you're telling the interpreter: a is a procedure with no arguments and I want to call it, and this was not the case in here, a is just a number.
Also, for readability's sake, it's a good idea to use [] instead of () to separate each of the conditions in a cond expression, as shown in my code above - but don't forget them, they're mandatory and in your code you forgot them in the first condition.
Other people have described what your mistake is and what you should do.
It is also instructive to consider how your code is actually run and why it produces the output you see. Because of your missing parentheses, the first case for your cond is (= b 0). The first thing (=) is taken as the condition. Everything in Scheme except #f is true, so this is always true. Since it is true, this case is evaluated. Specifically, the rest of the things in the parentheses is taken as (possible multiple) expressions to evaluate, as an implicit begin. So basically it evaluates (begin b 0). The result is the result of the last expression, 0.