[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Somehow I have got this "thunk" thing wrong.
From: |
Olivier Dion |
Subject: |
Re: Somehow I have got this "thunk" thing wrong. |
Date: |
Fri, 05 Mar 2021 19:31:14 -0500 |
On Fri, 05 Mar 2021, Tim Meehan <btmeehan@gmail.com> wrote:
> I wanted to store a thunk in a hashtable so that I could look up its key
> and then run it later. Something like this:
>
> #! /usr/bin/guile
> !#
>
> (use-modules (ice-9 hash-table))
>
> (define stuff (alist->hash-table
> '((a . (lambda () (display "event a\n")))
> (b . (lambda () (display "event b\n")))
> (c . (lambda () (display "event c\n"))))))
You've quoted the whole s-exp. Which means lambda is never applied.
You have to apply lambda in order to create a procedure.
>
> (define res (hash-ref stuff 'a))
> (res)
>
> But when I run it:
> Wrong type to apply: (lambda () (display "event a\n"))
You're trying to apply a list and not a procedure. This is because of
the quote mentioned above. In other words, you're doing this:
----------------------------------------------------------------------
(apply '(lambda () (display "event a\n")))
----------------------------------------------------------------------
Change the ' for ` and unquote the lambdas with ,. Like this:
----------------------------------------------------------------------
(define stuff (alist->hash-table
`((a . ,(lambda () (display "event a\n")))
(b . ,(lambda () (display "event b\n")))
(c . ,(lambda () (display "event c\n"))))))
----------------------------------------------------------------------
Or use the list procedure instead of quoting:
----------------------------------------------------------------------
#! /usr/bin/guile
!#
(use-modules (ice-9 hash-table))
(define stuff (alist->hash-table
(list (cons 'a (lambda () (display "event a\n")))
(cons 'b (lambda () (display "event b\n")))
(cons 'c (lambda () (display "event c\n"))))))
(define res (hash-ref stuff 'a))
(res)
----------------------------------------------------------------------
--
Olivier Dion
PolyMtl