nested lambda in scheme - function

I'm trying to define a function in scheme that prints a message when called, followed by a newline. To do this I've attempted to use nested lambda like this:
(define message
(lambda (msg)
(lambda (newL)
(newline)
)
(display msg))
)
However, when I do this, and call the function like:
(message "#f")
it only prints the #f, and does not create a newline. If I reverse the lambda orders in the function and swap the position of the newL and msg lambda's, then it only prints a newline and doesn't display the message!
The function is called in this block of code:
(define (permute upList)
(if (null? upList)
(message "#f")
;permutation code
)
)
The error message received when not using nested lambda's is as follows:
Error: call of non-procedure: #
Call history:
<syntax> (permute (quote ()))
<syntax> (quote ())
<syntax> (##core#quote ())
<eval> (permute (quote ()))
<eval> [permute] (null? upList)
<eval> [permute] (message "#f")
<eval> [message] ((display msg) (newline))
<eval> [message] (display msg)
<eval> [message] (newline) <--
Any help would be appreciated.

In this code, you only create a procedure object, which is then immediately discarded:
(define message
(lambda (msg)
(lambda (newL)
(newline))
(display msg)))
It's like doing:
(define message
(lambda (msg)
1234
(display msg)))
The 1234 here is evaluated, but the value is completely ignored.
If you have a procedure and you want to call it immediately, you have to wrap in an extra set of parentheses (because in Scheme, in general, parens represent application):
(define message
(lambda (msg)
((lambda (newL)
(newline)) #f)
(display msg)))
But, as others have pointed out, there's no need to create a nested lambda in this case. Plus, the procedure ignores its argument anyway, which is why I had to invent an argument to pass; I used #f because that's the typical "don't care" value. You can just do:
(define message
(lambda (msg)
(newline)
(display msg)))

Related

Emacs Lisp variables scoping

Let's consider the following functions:
(defun test (x)
"X."
(request "http://example.com"
:parser 'json-read
:complete (cl-function
(lambda (&key response &allow-other-keys)
(message "%s" x)))))
(defun test2 (x)
"X."
(funcall (cl-function (lambda (z) (message "%s" z))) x))
Calling (test2 3) Works fine and produces the desired message. Calling (test 3), however, fails with the following error:
error in process sentinel: let*: Symbol’s value as variable is void: x
error in process sentinel: Symbol’s value as variable is void: x
My guess is that request is a macro doing something weird to variable scoping. Unfortunately, the documentation does not mention anything like this. Is there a way to overcome that?
request is probably an ordinary function.
The problem is that the lambda you pass to it is not called immediately but is
saved and called later:
(defun make-function (x)
(lambda () (message "received %s" x)))
=> make-function
(defconst f (make-function 3))
=> f
(funcall f)
=> Lisp error: (void-variable x)
x that make-function bound no longer exists.
This is because by default Emacs uses dynamic binding and you need lexical binding to get the behavior you want.
If you add
;; -*- lexical-binding:t -*-
to the first line of your file, it will be compiled with lexical binding and
the code above will produce the message received 3 instead of an error.

elisp: Test an object is a function

I am trying to identify a safe way to check whether an object is a function (named or anonymous).
As functionp or fboundp do not work as I expected giving errors, I am trying with:
(defun function-check (x)
(and (boundp 'x)
(if (symbolp x) (fboundp x)
(functionp x))))
Apparently it works with several types of objects:
(setq lfun (lambda () "hello"))
(function-check lfun) ; -> t
(setq nfun 'buffer-name)
(function-check nfun) ; -> t
(setq slfun '(lambda () "hello"))
(function-check slfun) ; -> t
(function-check 'not-bound) ; -> safe nil
Anyway, looking at my code it seems too verbose and convoluted for such a simple task.
Is it possible to make it better?
Update:
As asked, I clarify what I mean with "functionp, fboundp do now work as I expected".
Say we want to detect a valid hook. This does not work:
(setq var 'buffer-name)
(functionp 'var) ;nil
(fboundp 'var) ;nil
We need to use:
(functionp var) ;t
(fboundp var) ;t
While this works, we need to make sure that var is not void, otherwise we get errors:
(functionp void-var) ;Lisp-error
(fboundp void-var) ;Lisp-error
Depending on the situations, this implies adding extra control code, compiling the code, etc.
A valid hook can be any callable object: macros, functions, lambdas are valid hooks. Anyway functionp does not work with macros:
(defmacro mac () "hello")
(functionp 'mac) ;nil
While fbound does not work with lambda expressions:
(functionp '(lambda () t)) ;t
(functionp (lambda () t)) ;t
(fboundp '(lambda () t)) ;Lisp error
(fboundp (lambda () t)) ;Lisp error
This happens also if assigning the expression to a variable:
(setq var '(lambda () t))
(functionp var) ;t
(fboundp var) ;Lisp error
which might require testing if var is a symbol.
As I understand, there is no straight way to test an object is callable, hence my attempt.
The (boundp 'x) check is a bit tautological here. If you're compiling your code with dynamic binding, (boundp 'x) will always be t, since x is bound when entering the function. If you're compiling your code with lexical binding, (boundp 'x) will probably be nil, unless you somehow create a "global" variable called x. In neither case will the result depend on the argument you pass to the function.
So I think you just need this:
(defun function-check (x)
(if (symbolp x)
(fboundp x)
(functionp x)))
That is, check that x is either a symbol that has a function binding, or a lambda function.
I found an interesting example of a function predicate used in the AUCTeX package.
(defun TeX-function-p (arg)
"Return non-nil if ARG is callable as a function."
(or (and (fboundp 'byte-code-function-p)
(byte-code-function-p arg))
(and (listp arg)
(eq (car arg) 'lambda))
(and (symbolp arg)
(fboundp arg))))
This test is used in AUCTeX before calling the (component of) TeX commands obtained by parsing the alist TeX-expand-list.
If an expansion found in the alist is a function, then it is called with:
(apply expansion arguments)
TeX-function-p is thorough, as TeX-expand-list is huge and customisable, and expansions might also result in objects which are not symbols or symbols which are not bound.
This function answers my question in that it shows that functionp might not always be sufficient to test for a callable object.

How to pass elisp function or command into function parameters? [duplicate]

I'm trying to pass one method to another in elisp, and then
have that method execute it. Here is an example:
(defun t1 ()
"t1")
(defun t2 ()
"t1")
(defun call-t (t)
; how do I execute "t"?
(t))
; How do I pass in method reference?
(call-t 't1)
First, I'm not sure that naming your function t is helping as 't' is used as the truth value in lisp.
That said, the following code works for me:
(defun test-func-1 () "test-func-1"
(interactive "*")
(insert-string "testing callers"))
(defun func-caller (callee)
"Execute callee"
(funcall callee))
(func-caller 'test-func-1)
Please note the use of 'funcall', which triggers the actual function call.
The note towards the end of "§13.7 Anonymous Functions" in the Emacs Lisp manual says that you can quote functions with #' instead of ' to signal to the byte compiler that the symbol always names a function.
Above answers are okey, but you can do something more interesting with defmacro, wich evaluates functions later for some reason:
(defun n1 ()
"n1")
(defmacro call-n (n)
(apply n))
(call-n (n1))
A practical example with a for loop that takes any amount of functions and their arguments:
(defmacro for (i &optional i++ &rest body)
"c-like for-loop"
(unless (numberp i++) (push i++ body) (setq i++ 1))
(while (/= i 0)
(let ((args 0))
(while (nth args body)
(apply (car (nth args body))
(cdr (nth args body)))
(setq args (1+ args))))
(setq i (- i i++))
)
)

LISP dynamically define functions

I want to define a function with a parameter that defines another function with that parameter as the name.
example that dont work:
(DEFUN custom (name op const var)
(DEFUN name (var) (op const var)))
The problem is that name isnt evaluated and so the function that is defined is always called name.
I know that FUNCALL and APPLY can evaluate parameter dynamically, but i don't know how to call FUNCALL DEFUN... correctly.
I don't think you can use nested defuns.
You can either use a defun to return a lambda:
(defun custom (op const)
(lambda (arg) (funcall op const arg)))
and then use fdefinition:
(setf (fdefinition '+42) (custom '+ '42))
or use defmacro:
(defmacro custom (name op const)
(let ((arg (gensym)))
`(defun ,name (,arg)
(,op ,const ,arg))))
(custom +42 + 42)
PS. I think you need to explain why you are trying to do this, then we will be able to explain your options better.
It seems to me you might want to curry a function. Imagine you did this:
(defun curry (op arg1)
(lambda (&rest args) (apply op (cons arg1 args))))
(funcall (curry #'+ 10) 20) ; ==> 30
(mapcar (curry #'+ 10) '(1 2 3 4)) ; ==> (11 12 13 14)
Now defun makes a function in the global namespace always. It's not like in Scheme where it creates a closure. To do the same as defun we use symbol-function and setf:
(defun create-curried (name op arg1)
(setf (symbol-function name)
(lambda (&rest args) (apply op (cons arg1 args)))))
(create-curried '+x #'+ 10) ; ==> function
(+x 20) ; ==> 30
;; since it's a function, it even works with higher order functions
(mapcar create-curried '(+x -x /x *x) (list #'+ #'- #'/ #'*) '(10 10 10 10))
(/x 2) ; ==> 5
Last. With macros you can prettify it.
(defmacro defun-curried (newname oldname arg)
(if (and (symbolp newname) (symbolp oldname))
`(create-curried ',newname (function ,oldname) ,arg)
(error "Newname and Oldname need to be symbols")))
(defun-curried +xx + 20)
(+xx 10) ; ==> 30
oldname is taken from the lexical scope so you may use flet or labels with this but it ends up being global, just like with defun.
The main problem is that DEFUN isn't a function, it's a macro that treats its arguments specially (specifically, it doesn't evaluate "the function name", "the argument list", not "the function body").
You could probably make something work by careful use of (setf (symbol-function ...) ...), something like:
(defun define-custom-function (name op const)
(setf (symbol-function name) (lambda (var) (funcall op const var))))
This binds the function definition of the symbol to an anonymous function that calls your "operator" on your fed-in constant.
* (defun define-custom-function (name op const)
(setf (symbol-function name) (lambda (var) (funcall op const var))))
DEFINE-CUSTOM-FUNCTION
* (define-custom-function 'add3 #'+ 3)
#<CLOSURE (LAMBDA (VAR) :IN DEFINE-CUSTOM-FUNCTION) {1002A4760B}>
* (add3 5)
8
However, unless you absolutely need to define (or re-define) these custom functions dynamically, you are probably better off defining a custom DEFUN-like macro.

How variables are sent to the functions in scheme?

I'm new to scheme. When I run the following code
(define lst '(1))
(let ((func1 (lambda lst
(begin (display lst)
lst))))
(begin (display lst)
(func1 lst)))
I got (1)((1))'((1)), which means lst displays as (1) when called in the fourth line, but when send it to the function func1, it becomes ((1)). What exactly happened here?
(lambda Args E) means: bind the variable-length argument list of this function to Args. E.g.
(define f (lambda args `(got ,(length args) arguments)))
(display (f 'foo 'bar 'baz))
will print (got 3 arguments). If you change the lambda expression to
(lambda (lst) (begin (display lst) lst))
;;; ^---^
then the function will print, and return, its single argument.
In a lambda form, when you write this:
(lambda x <body>)
... you're declaring that x is a list of parameters with zero or more elements. On the other hand, this:
(lambda (x) <body>)
... is stating that x is a single parameter. In the question, this code (the begin is unnecessary for the body part in a lambda):
((lambda lst (display lst) lst) '(1))
... will display and return the list of parameters; if we pass '(1) it will evaluate to '((1)): a list with a single element which happens to be a list.
Surely you intended to do this instead:
((lambda (lst) (display lst) lst) '(1))
... which will display and return the single parameter it receives - in case of passing '(1) the above expression will evaluate to '(1), the parameter itself.