racket how to define function as another function in procedure - function

I am trying to make a helper function that will take input of switched syntax.
Helper function needs to be able to do:
> (num sqr) ; where num=6, and sqr is the math function square.
36
Originally, the built-in syntax would be:
>(sqr num) ; where num=6
36
Since I cannot declare 'num' as a function and a variable at the same time, I will need to nest another procedure into it. Below is what I have so far:
(define (num func)
(display func + 6))
Now, I know that 'display' won't easily do what I'd like it to do unlike other programming languages. Is there another method in place of 'display' that I can use? I think this is the easiest way to do it, but I am new so I'm not sure which is an appropriate method. 'func' will need to be able to take math functions like 'sqr' 'sqrt' 'add1'...etc.

If you just want (num sqr) to work like in your code you can do this:
(define (num fun)
(fun 6))
(num sqr) ; ==> 36
(num add1) ; ==> 7
But num won't be 6.
A solution might be to make yourself a module language, perhaps called #!lefthanded-racket where the parser for code just reverses all lists. Thus you can supply it code like:
#!lefthanded-racket
(6 num define)
(num sqr) ; ==> 36
(num add1) ; ==> 7
((((((1 y -) x ack) (1 x -) ack) (y x))
(2 (1 _))
((y 2 *) (y 0))
(0 (0 _))
(y x) match*)
(y x ack) define)
(4 2 ack) ; ==> 65536
For the simple solution, where you just override the default reader and deep reverse the lists you'll have problems with dotted lists. In order to get that right you need to write a parser.
The code that is run won't be in reverse, only the code you write. There is some documentation on how to create your own language. Also this practical example might be helpful too.

Do you mean something like this?
#lang racket
(define ((partial func) arg)
(func arg))
((partial sqr) 6)
The output is 36.

Related

Why is cond function not printing in scheme?

I am very new to scheme, and I am having trouble getting simple cond functions that I make to print in DrRacket ide. When I run these two functions:
(define (test x)
(cond
[(zero? x) (error "doesn't get here, either")]
[(positive? x) 'here]))
(define (compare x y)
(cond [(equal? x y) "Is Equal"]))
it prints:
> test 12
#<procedure:test>
12
> compare 12 12
#<procedure:compare>
12
12
Why will it not output any of the errors, or "Is Equal"? It works fine if I run the cond statements directly and replace the variables.
You're not actually calling the new procedures, you must surround the procedure name and its arguments between brackets (), just as you did with all the other procedures you're using in your solution! This is the way:
(test 12)
=> 'here
(compare 12 12)
=> "Is Equal"

Error of calling functions in Scheme

I am trying to define two functions using Scheme. One is the close_to function which looks like this:
(define (close_to x y)(if(< (abs (- x y)) 0.0001)(#t)#f))
it should return true if the number x and y has a difference that is smaller than 0.0001 and false otherwise. However, it keeps throwing the error:
function call: expected a function after the open parenthesis, but received true
when I call it
(close_to 4 3.99999999)
The second function is the improve function which looks like this:
(define (improve x y)(average y /(x y)))
it should return the average of y and x/y. Similarly, I am getting the error:
function call: expected a function after the open parenthesis, but received 1
when I call it
(improve 1 2)
What am I doing wrong? Can anyone help me?
Your problem is the (#t) and (#f).
#t is not a function. Rather, rewrite the first one like this:
(define (close_to x y)
(if (< (abs (- x y)) 0.0001)
#t
#f))
The other is an exercise for the reader.

recursive definition of map in common lisp [duplicate]

This question already has answers here:
Why do we need funcall in Lisp?
(3 answers)
Closed 8 years ago.
I was expecting the Scheme approach:
(defun mmap (f xs)
(if (equal xs NIL)
'()
(cons (f (car xs)) (mmap f (cdr xs)))))
but i get a compiler warning
;Compiler warnings for ".../test.lisp" :
; In MMAP: Undefined function F
I can see that I need to make the compiler aware that f is a function. Does this have anything to do with #'?
Common Lisp is a LISP2. It means variables that are in the first element of the form is evaluated in a function namespace while everything else is evaluated from a variable namespace. Basically it means you can use the same name as a function in your arguments:
(defun test (list)
(list list list))
Here the first list is looked up in the function namespace and the other two arguments are looked up in the variable namespace. First and the rest become two different values because they are fetched from different places. If you'd do the same in Scheme which is a LISP1:
(define (test list)
(list list list))
And pass a value that is not a procedure that takes two arguments, then you'll get an error saying list is not a procedure.
A function with name x in the function namespace can be fetched from other locations by using a special form (function x). Like quote function has syntax sugar equivalent so you can write #'x. You can store functions in the variable namespace (setq fun #'+) and you can pass it to higher order functions like mapcar (CL version of Scheme map). Since first element in a form is special there is a primitive function funcall that you can use when the function is bound in the variable namespace: (funcall fun 2 3) ; ==> 5
(defun my-mapcar (function list)
(if list
(cons (funcall function (car list))
(my-mapcar function (cdr list)))
nil))
(my-mapcar #'list '(1 2 3 4)) ; ==> ((1) (2) (3) (4))
A version using loop which is the only way to be sure not to blow the stack in CL:
(defun my-mapcar (function list)
(loop :for x :in list
:collect (funcall function x)))
(my-mapcar #'list '(1 2 3 4)) ; ==> ((1) (2) (3) (4))
Of course, mapcar can take multiple list arguments and the function map is like mapcar but it works with all sequences (lists, arrays, strings)
;; zip
(mapcar #'list '(1 2 3 4) '(a b c d)) ; ==> ((1 a) (2 b) (3 c) (4 d))
;; slow way to uppercase a string
(map 'string #'char-upcase "banana") ; ==> "BANANA"
functions in CL that accepts functions as arguments also accept symbols. Eg. #'+ is a function while '+ is a symbol. What happens is that it retrieves #'+ by fetching the function represented by + in the global namespace. Thus:
(flet ((- (x) (* x x)))
(list (- 5) (funcall #'- 5) (funcall '- 5))) ; ==> (25 25 -5)
Trivia: I think the number in LISP1 and LISP2 refer to the number of namespaces rather than versions. The very first LISP interpereter had only one namespace, but dual namespace was a feature of LISP 1.5. It was he last LISP version before commercial versions took over. A LISP2 was planned but was never finished. Scheme was originally written as a interpreter in MacLisp (Which is based on LISP 1.5 and is a LISP2). Kent Pittman compared the two approaches in 1988.

Defining a Racket Function?

I'm supposed to define the function n! (N-Factorial). The thing is I don't know how to.
Here is what I have so far, can someone please help with this? I don't understand the conditionals in Racket, so an explanation would be great!
(define fact (lambda (n) (if (> n 0)) (* n < n)))
You'll have to take a good look at the documentation first, this is a very simple example but you have to understand the basics before attempting a solution, and make sure you know how to write a recursive procedure. Some comments:
(define fact
(lambda (n)
(if (> n 0)
; a conditional must have two parts:
; where is the consequent? here goes the advance of the recursion
; where is the alternative? here goes the base case of the recursion
)
(* n < n))) ; this line is outside the conditional, and it's just wrong
Notice that the last expression is incorrect, I don't know what it's supposed to do, but as it is it'll raise an error. Delete it, and concentrate on writing the body of the conditional.
The trick with scheme (or lisp) is to understand each little bit between each set of brackets as you build them up into more complex forms.
So lets start with the conditionals. if takes 3 arguments. It evaluates the first, and if that's true, if returns the second, and if the first argument is false it returns the third.
(if #t "some value" "some other value") ; => "some value"
(if #f "some value" "some other value") ; => "some other value"
(if (<= 1 0) "done" "go again") ; => "go again"
cond would work too - you can read the racket introduction to conditionals here: http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Conditionals_with_if__and__or__and_cond%29
You can define functions in two different ways. You're using the anonymous function approach, which is fine, but you don't need a lambda in this case, so the simpler syntax is:
(define (function-name arguments) result)
For example:
(define (previous-number n)
(- n 1))
(previous-number 3) ; => 2
Using a lambda like you have achieves the same thing, using different syntax (don't worry about any other differences for now):
(define previous-number* (lambda (n) (- n 1)))
(previous-number* 3) ; => 2
By the way - that '*' is just another character in that name, nothing special (see http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Identifiers%29). A '!' at the end of a function name often means that that function has side effects, but n! is a fine name for your function in this case.
So lets go back to your original question and put the function definition and conditional together. We'll use the "recurrence relation" from the wiki definition because it makes for a nice recursive function: If n is less than 1, then the factorial is 1. Otherwise, the factorial is n times the factorial of one less than n. In code, that looks like:
(define (n! n)
(if (<= n 1) ; If n is less than 1,
1 ; then the factorial is 1
(* n (n! (- n 1))))) ; Otherwise, the factorial is n times the factorial of one less than n.
That last clause is a little denser than I'd like, so lets just work though it down for n = 2:
(define n 2)
(* n (n! (- n 1)))
; =>
(* 2 (n! (- 2 1)))
(* 2 (n! 1))
(* 2 1)
2
Also, if you're using Racket, it's really easy to confirm that it's working as we expect:
(check-expect (n! 0) 1)
(check-expect (n! 1) 1)
(check-expect (n! 20) 2432902008176640000)

Any way to "visualize" a thunk/function? Or how to view a function for a general argument

I'm not totally sure how to ask this, but is there a way to show the structure of a thunk?
For example
f x = x + 2
g x = 3 x
compo x = f (g x)
ans = compo 5
-- result: (3 * 5) + 2 = 17
Is there any way I could "see" the thunk for ans? As in, I could see the process of the beta reduction for compo or like the "general" form.
I would like to see, for example:
compo n
--> (3 * n) + 2
As in, if I had a function compo x, I would like to view that it is decomposed to (3*n)+2.
For example, in Mathematica:
f[x_] := x+2;
g[x_] := 3*x;
compo[x_] := f[g[x]];
compo[n]
(%
--> (3 * n) + 2
%)
There is the ghc-vis package on hackage which show a visualization of your heap and of unevaluated thunks.
See the package on hackage or the Homepage (which contains rather impressive examples).
If you just want to see the sequence of reductions, you could try using the GHCi interactive debugger. (It's in the GHC manual somewhere.) It's not nearly as easy as your typical IDE debugger, but it more or less works...
In general (we are talking about Haskell code) I think it has no sense, the final thunk stream will be different for different input data and, on the other hand, functions are expanded partially (functions are not only simple expressions).
Anyway, you can simulate it (but ugly)
Prelude> :set -XQuasiQuotes
Prelude> :set -XTemplateHaskell
Prelude> import Language.Haskell.TH
Prelude> import Language.Haskell.TH.Quote
Prelude> runQ [| $([|\x -> 3 * x|]) . $([|\y -> y + 2|]) |]
InfixE (Just (LamE [VarP x_0] (InfixE (Just (LitE (IntegerL 3))) (VarE GHC.Num.*) (Just (VarE x_0))))) (VarE GHC.Base..) (Just (LamE [VarP y_1] (InfixE (Just (VarE y_1)) (VarE GHC.Num.+) (Just (LitE (IntegerL 2))))))