help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Real-life examples of lexical binding in Emacs Lisp


From: Tassilo Horn
Subject: Re: Real-life examples of lexical binding in Emacs Lisp
Date: Wed, 17 Jun 2015 21:30:01 +0200
User-agent: Gnus/5.130014 (Ma Gnus v0.14) Emacs/25.0.50 (gnu/linux)

Andreas Röhler <andreas.roehler@easy-emacs.de> writes:

> ;;; -*- lexical-binding: t; -*-
>
> (defun my-map (f l)
>   (if l (cons (funcall f (car l)) (my-map f (cdr l)))))
>
> (defun my-function (input)
>   (let ((l ()))
>     (my-map (lambda (x) (unless (memq x l) (error "invalid mapping")))
>         input)))
>
> (my-function '(4 5))
>
> Got identic results also without lexical-binding seen here.  l is
> taken from inside lambda in both modes.

You have to byte-compile.  Then you get for the lexical version:

--8<---------------cut here---------------start------------->8---
byte code for my-function:
  doc:   ...
  args: 257
0       constant  nil
1       constant  my-map
2       constant  make-byte-code
3       constant  257
4       constant  "\211\300>?\205\n.\301\302!\207"
5       constant  vconcat
6       constant  vector
7       stack-ref 6
9       call      1
10      constant  [error "invalid mapping"]
11      call      2
12      constant  3
13      constant  "\n\n(fn X)"
14      call      5
15      stack-ref 3
16      call      2
17      return    
--8<---------------cut here---------------end--------------->8---

That gives:

  (my-function '(4 5)) => Lisp error: (error "invalid mapping")

For the dynamic version:

--8<---------------cut here---------------start------------->8---
byte code for my-function:
  args: (input)
0       constant  nil
1       varbind   l
2       constant  my-map
3       constant  <compiled-function>
      args: (x)
    0       varref    x
    1       varref    l
    2       memq      
    3       not       
    4       goto-if-nil-else-pop 1
    7       constant  error
    8       constant  "invalid mapping"
    9       call      1
    10:1    return    

4       varref    input
5       call      2
6       unbind    1
7       return    
--8<---------------cut here---------------end--------------->8---

Note the varref l.  When the lambda is called in the dynamic version, l
will refer to the l argument from my-map.

That gives:

  (my-function '(4 5)) => (nil nil)

Bye,
Tassilo



reply via email to

[Prev in Thread] Current Thread [Next in Thread]