monads.scm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2013, 2014, 2015, 2017, 2022 Ludovic Courtès <ludo@gnu.org>
  3. ;;;
  4. ;;; This file is part of GNU Guix.
  5. ;;;
  6. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  7. ;;; under the terms of the GNU General Public License as published by
  8. ;;; the Free Software Foundation; either version 3 of the License, or (at
  9. ;;; your option) any later version.
  10. ;;;
  11. ;;; GNU Guix is distributed in the hope that it will be useful, but
  12. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;;; GNU General Public License for more details.
  15. ;;;
  16. ;;; You should have received a copy of the GNU General Public License
  17. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  18. (define-module (guix monads)
  19. #:use-module ((system syntax)
  20. #:select (syntax-local-binding))
  21. #:use-module (ice-9 match)
  22. #:use-module (srfi srfi-1)
  23. #:use-module (srfi srfi-9)
  24. #:use-module (srfi srfi-26)
  25. #:export (;; Monads.
  26. define-monad
  27. monad?
  28. monad-bind
  29. monad-return
  30. template-directory
  31. ;; Syntax.
  32. >>=
  33. return
  34. with-monad
  35. mlet
  36. mlet*
  37. mbegin
  38. mwhen
  39. munless
  40. mparameterize
  41. lift0 lift1 lift2 lift3 lift4 lift5 lift6 lift7 lift
  42. listm
  43. foldm
  44. mapm
  45. sequence
  46. anym
  47. ;; Concrete monads.
  48. %identity-monad
  49. %state-monad
  50. state-return
  51. state-bind
  52. current-state
  53. set-current-state
  54. state-push
  55. state-pop
  56. run-with-state))
  57. ;;; Commentary:
  58. ;;;
  59. ;;; This module implements the general mechanism of monads, and provides in
  60. ;;; particular an instance of the "state" monad. The API was inspired by that
  61. ;;; of Racket's "better-monads" module (see
  62. ;;; <http://planet.racket-lang.org/package-source/toups/functional.plt/1/1/planet-docs/better-monads-guide/index.html>).
  63. ;;; The implementation and use case were influenced by Oleg Kysielov's
  64. ;;; "Monadic Programming in Scheme" (see
  65. ;;; <http://okmij.org/ftp/Scheme/monad-in-Scheme.html>).
  66. ;;;
  67. ;;; Code:
  68. ;; Record type for monads manipulated at run time.
  69. (define-record-type <monad>
  70. (make-monad bind return)
  71. monad?
  72. (bind monad-bind)
  73. (return monad-return)) ; TODO: Add 'plus' and 'zero'
  74. (define-syntax define-monad
  75. (lambda (s)
  76. "Define the monad under NAME, with the given bind and return methods."
  77. (define prefix (string->symbol "% "))
  78. (define (make-rtd-name name)
  79. (datum->syntax name
  80. (symbol-append prefix (syntax->datum name) '-rtd)))
  81. (syntax-case s (bind return)
  82. ((_ name (bind b) (return r))
  83. (with-syntax ((rtd (make-rtd-name #'name)))
  84. #`(begin
  85. (define rtd
  86. ;; The record type, for use at run time.
  87. (make-monad b r))
  88. ;; Instantiate all the templates, specialized for this monad.
  89. (template-directory instantiations name)
  90. (define-syntax name
  91. ;; An "inlined record", for use at expansion time. The goal is
  92. ;; to allow 'bind' and 'return' to be resolved at expansion
  93. ;; time, in the common case where the monad is accessed
  94. ;; directly as NAME.
  95. (lambda (s)
  96. (syntax-case s (%bind %return)
  97. ((_ %bind) #'b)
  98. ((_ %return) #'r)
  99. (_ #'rtd))))))))))
  100. ;; Expansion- and run-time state of the template directory. This needs to be
  101. ;; available at run time (and not just at expansion time) so we can
  102. ;; instantiate templates defined in other modules, or use instances defined
  103. ;; elsewhere.
  104. (eval-when (load expand eval)
  105. ;; Mapping of syntax objects denoting the template to a pair containing (1)
  106. ;; the syntax object of the parameter over which it is templated, and (2)
  107. ;; the syntax of its body.
  108. (define-once %templates (make-hash-table))
  109. (define (register-template! name param body)
  110. (hash-set! %templates name (cons param body)))
  111. ;; List of template instances, where each entry is a triplet containing the
  112. ;; syntax of the name, the actual parameter for which the template is
  113. ;; specialized, and the syntax object referring to this specialization (the
  114. ;; procedure's identifier.)
  115. (define-once %template-instances '())
  116. (define (register-template-instance! name actual instance)
  117. (set! %template-instances
  118. (cons (list name actual instance) %template-instances))))
  119. (define-syntax template-directory
  120. (lambda (s)
  121. "This is a \"stateful macro\" to register and lookup templates and
  122. template instances."
  123. (define location
  124. (syntax-source s))
  125. (define current-info-port
  126. ;; Port for debugging info.
  127. (const (%make-void-port "w")))
  128. (define location-string
  129. (format #f "~a:~a:~a"
  130. (assq-ref location 'filename)
  131. (and=> (assq-ref location 'line) 1+)
  132. (assq-ref location 'column)))
  133. (define (matching-instance? name actual)
  134. (match-lambda
  135. ((name* instance-param proc)
  136. (and (free-identifier=? name name*)
  137. (or (equal? actual instance-param)
  138. (and (identifier? actual)
  139. (identifier? instance-param)
  140. (free-identifier=? instance-param
  141. actual)))
  142. proc))))
  143. (define (instance-identifier name actual)
  144. (define stem
  145. (string-append
  146. " "
  147. (symbol->string (syntax->datum name))
  148. (if (identifier? actual)
  149. (string-append " " (symbol->string (syntax->datum actual)))
  150. "")
  151. " instance"))
  152. (datum->syntax actual (string->symbol stem)))
  153. (define (instance-definition name template actual)
  154. (match template
  155. ((formal . body)
  156. (let ((instance (instance-identifier name actual)))
  157. (format (current-info-port)
  158. "~a: info: specializing '~a' for '~a' as '~a'~%"
  159. location-string
  160. (syntax->datum name) (syntax->datum actual)
  161. (syntax->datum instance))
  162. (register-template-instance! name actual instance)
  163. #`(begin
  164. (define #,instance
  165. (let-syntax ((#,formal (identifier-syntax #,actual)))
  166. #,body))
  167. ;; Generate code to register the thing at run time.
  168. (register-template-instance! #'#,name #'#,actual
  169. #'#,instance))))))
  170. (syntax-case s (register! lookup exists? instantiations)
  171. ((_ register! name param body)
  172. ;; Register NAME as a template on PARAM with the given BODY.
  173. (begin
  174. (register-template! #'name #'param #'body)
  175. ;; Generate code to register the template at run time. XXX: Because
  176. ;; of this, BODY must not contain ellipses.
  177. #'(register-template! #'name #'param #'body)))
  178. ((_ lookup name actual)
  179. ;; Search for an instance of template NAME for this ACTUAL parameter.
  180. ;; On success, expand to the identifier of the instance; otherwise
  181. ;; expand to #f.
  182. (any (matching-instance? #'name #'actual) %template-instances))
  183. ((_ exists? name actual)
  184. ;; Likewise, but return a Boolean.
  185. (let ((result (->bool
  186. (any (matching-instance? #'name #'actual)
  187. %template-instances))))
  188. (unless result
  189. (format (current-warning-port)
  190. "~a: warning: no specialization of template '~a' for '~a'~%"
  191. location-string
  192. (syntax->datum #'name) (syntax->datum #'actual)))
  193. result))
  194. ((_ instantiations actual)
  195. ;; Expand to the definitions of all the existing templates
  196. ;; specialized for ACTUAL.
  197. #`(begin
  198. #,@(hash-map->list (cut instance-definition <> <> #'actual)
  199. %templates))))))
  200. (define-syntax define-template
  201. (lambda (s)
  202. "Define a template, which is a procedure that can be specialized over its
  203. first argument. In our case, the first argument is typically the identifier
  204. of a monad.
  205. Defining templates for procedures like 'mapm' allows us to make have a
  206. specialized version of those procedures for each monad that we define, such
  207. that calls to:
  208. (mapm %state-monad proc lst)
  209. automatically expand to:
  210. (#{ mapm %state-monad instance}# proc lst)
  211. Here, #{ mapm %state-monad instance}# is specialized for %state-monad, and
  212. thus it contains inline calls to %state-bind and %state-return. This avoids
  213. repeated calls to 'struct-ref' to get the 'bind' and 'return' procedure of the
  214. monad, and allows 'bind' and 'return' to be inlined, which in turn allows for
  215. more optimizations."
  216. (syntax-case s ()
  217. ((_ (name arg0 args ...) body ...)
  218. (with-syntax ((generic-name (datum->syntax
  219. #'name
  220. (symbol-append '#{ %}#
  221. (syntax->datum #'name)
  222. '-generic)))
  223. (original-name #'name))
  224. #`(begin
  225. (template-directory register! name arg0
  226. (lambda (args ...)
  227. body ...))
  228. (define (generic-name arg0 args ...)
  229. ;; The generic instance of NAME, for when no specialization was
  230. ;; found.
  231. body ...)
  232. (define-syntax name
  233. (lambda (s)
  234. (syntax-case s ()
  235. ((_ arg0* args ...)
  236. ;; Expand to either the specialized instance or the
  237. ;; generic instance of template ORIGINAL-NAME.
  238. #'(if (template-directory exists? original-name arg0*)
  239. ((template-directory lookup original-name arg0*)
  240. args ...)
  241. (generic-name arg0* args ...)))
  242. (_
  243. #'generic-name))))))))))
  244. (define-syntax-parameter >>=
  245. ;; The name 'bind' is already taken, so we choose this (obscure) symbol.
  246. (lambda (s)
  247. (syntax-violation '>>= ">>= (bind) used outside of 'with-monad'" s)))
  248. (define-syntax-parameter return
  249. (lambda (s)
  250. (syntax-violation 'return "return used outside of 'with-monad'" s)))
  251. (define-syntax-rule (bind-syntax bind)
  252. "Return a macro transformer that handles the expansion of '>>=' expressions
  253. using BIND as the binary bind operator.
  254. This macro exists to allow the expansion of n-ary '>>=' expressions, even
  255. though BIND is simply binary, as in:
  256. (with-monad %state-monad
  257. (>>= (return 1)
  258. (lift 1+ %state-monad)
  259. (lift 1+ %state-monad)))
  260. "
  261. (lambda (stx)
  262. (define (expand body)
  263. (syntax-case body ()
  264. ((_ mval mproc)
  265. #'(bind mval mproc))
  266. ((x mval mproc0 mprocs (... ...))
  267. (expand #'(>>= (>>= mval mproc0)
  268. mprocs (... ...))))))
  269. (expand stx)))
  270. (define-syntax with-monad
  271. (lambda (s)
  272. "Evaluate BODY in the context of MONAD, and return its result."
  273. (syntax-case s ()
  274. ((_ monad body ...)
  275. (eq? 'macro (syntax-local-binding #'monad))
  276. ;; MONAD is a syntax transformer, so we can obtain the bind and return
  277. ;; methods by directly querying it.
  278. #'(syntax-parameterize ((>>= (bind-syntax (monad %bind)))
  279. (return (identifier-syntax (monad %return))))
  280. body ...))
  281. ((_ monad body ...)
  282. ;; MONAD refers to the <monad> record that represents the monad at run
  283. ;; time, so use the slow method.
  284. #'(syntax-parameterize ((>>= (bind-syntax
  285. (monad-bind monad)))
  286. (return (identifier-syntax
  287. (monad-return monad))))
  288. body ...)))))
  289. (define-syntax mlet*
  290. (syntax-rules (->)
  291. "Bind the given monadic values MVAL to the given variables VAR. When the
  292. form is (VAR -> VAL), bind VAR to the non-monadic value VAL in the same way as
  293. 'let'."
  294. ;; Note: the '->' symbol corresponds to 'is:' in 'better-monads.rkt'.
  295. ((_ monad () body ...)
  296. (with-monad monad body ...))
  297. ((_ monad ((var mval) rest ...) body ...)
  298. (with-monad monad
  299. (>>= mval
  300. (lambda (var)
  301. (mlet* monad (rest ...)
  302. body ...)))))
  303. ((_ monad ((var -> val) rest ...) body ...)
  304. (let ((var val))
  305. (mlet* monad (rest ...)
  306. body ...)))))
  307. (define-syntax mlet
  308. (lambda (s)
  309. (syntax-case s ()
  310. ((_ monad ((var mval ...) ...) body ...)
  311. (with-syntax (((temp ...) (generate-temporaries #'(var ...))))
  312. #'(mlet* monad ((temp mval ...) ...)
  313. (let ((var temp) ...)
  314. body ...)))))))
  315. (define-syntax mbegin
  316. (syntax-rules (%current-monad)
  317. "Bind MEXP and the following monadic expressions in sequence, returning
  318. the result of the last expression. Every expression in the sequence must be a
  319. monadic expression."
  320. ((_ %current-monad mexp)
  321. mexp)
  322. ((_ %current-monad mexp rest ...)
  323. (>>= mexp
  324. (lambda (unused-value)
  325. (mbegin %current-monad rest ...))))
  326. ((_ monad mexp)
  327. (with-monad monad
  328. mexp))
  329. ((_ monad mexp rest ...)
  330. (with-monad monad
  331. (>>= mexp
  332. (lambda (unused-value)
  333. (mbegin monad rest ...)))))))
  334. (define-syntax mwhen
  335. (syntax-rules ()
  336. "When CONDITION is true, evaluate the sequence of monadic expressions
  337. MEXP0..MEXP* as in an 'mbegin'. When CONDITION is false, return *unspecified*
  338. in the current monad. Every expression in the sequence must be a monadic
  339. expression."
  340. ((_ condition mexp0 mexp* ...)
  341. (if condition
  342. (mbegin %current-monad
  343. mexp0 mexp* ...)
  344. (return *unspecified*)))))
  345. (define-syntax munless
  346. (syntax-rules ()
  347. "When CONDITION is false, evaluate the sequence of monadic expressions
  348. MEXP0..MEXP* as in an 'mbegin'. When CONDITION is true, return *unspecified*
  349. in the current monad. Every expression in the sequence must be a monadic
  350. expression."
  351. ((_ condition mexp0 mexp* ...)
  352. (if condition
  353. (return *unspecified*)
  354. (mbegin %current-monad
  355. mexp0 mexp* ...)))))
  356. (define-syntax mparameterize
  357. (syntax-rules ()
  358. "This form implements dynamic scoping, similar to 'parameterize', but in a
  359. monadic context."
  360. ((_ monad ((parameter value) rest ...) body ...)
  361. (let ((old-value (parameter)))
  362. (mbegin monad
  363. ;; XXX: Non-local exits are not correctly handled.
  364. (return (parameter value))
  365. (mlet monad ((result (mparameterize monad (rest ...) body ...)))
  366. (parameter old-value)
  367. (return result)))))
  368. ((_ monad () body ...)
  369. (mbegin monad body ...))))
  370. (define-syntax define-lift
  371. (syntax-rules ()
  372. ((_ liftn (args ...))
  373. (define-syntax liftn
  374. (lambda (s)
  375. "Lift PROC to MONAD---i.e., return a monadic function in MONAD."
  376. (syntax-case s ()
  377. ((liftn proc monad)
  378. ;; Inline the result of lifting PROC, such that 'return' can in
  379. ;; turn be open-coded.
  380. #'(lambda (args ...)
  381. (with-monad monad
  382. (return (proc args ...)))))
  383. (id
  384. (identifier? #'id)
  385. ;; Slow path: Return a closure-returning procedure (we don't
  386. ;; guarantee (eq? LIFTN LIFTN), but that's fine.)
  387. #'(lambda (proc monad)
  388. (lambda (args ...)
  389. (with-monad monad
  390. (return (proc args ...))))))))))))
  391. (define-lift lift0 ())
  392. (define-lift lift1 (a))
  393. (define-lift lift2 (a b))
  394. (define-lift lift3 (a b c))
  395. (define-lift lift4 (a b c d))
  396. (define-lift lift5 (a b c d e))
  397. (define-lift lift6 (a b c d e f))
  398. (define-lift lift7 (a b c d e f g))
  399. (define (lift proc monad)
  400. "Lift PROC, a procedure that accepts an arbitrary number of arguments, to
  401. MONAD---i.e., return a monadic function in MONAD."
  402. (lambda args
  403. (with-monad monad
  404. (return (apply proc args)))))
  405. (define-template (foldm monad mproc init lst)
  406. "Fold MPROC over LST and return a monadic value seeded by INIT.
  407. (foldm %state-monad (lift2 cons %state-monad) '() '(a b c))
  408. => '(c b a) ;monadic
  409. "
  410. (with-monad monad
  411. (let loop ((lst lst)
  412. (result init))
  413. (match lst
  414. (()
  415. (return result))
  416. ((head . tail)
  417. (>>= (mproc head result)
  418. (lambda (result)
  419. (loop tail result))))))))
  420. (define-template (mapm monad mproc lst)
  421. "Map MPROC over LST and return a monadic list.
  422. (mapm %state-monad (lift1 1+ %state-monad) '(0 1 2))
  423. => (1 2 3) ;monadic
  424. "
  425. ;; XXX: We don't use 'foldm' because template specialization wouldn't work
  426. ;; in this context.
  427. (with-monad monad
  428. (let mapm ((lst lst)
  429. (result '()))
  430. (match lst
  431. (()
  432. (return (reverse result)))
  433. ((head . tail)
  434. (>>= (mproc head)
  435. (lambda (head)
  436. (mapm tail (cons head result)))))))))
  437. (define-template (sequence monad lst)
  438. "Turn the list of monadic values LST into a monadic list of values, by
  439. evaluating each item of LST in sequence."
  440. (with-monad monad
  441. (let seq ((lstx lst)
  442. (result '()))
  443. (match lstx
  444. (()
  445. (return (reverse result)))
  446. ((head . tail)
  447. (>>= head
  448. (lambda (item)
  449. (seq tail (cons item result)))))))))
  450. (define-template (anym monad mproc lst)
  451. "Apply MPROC to the list of values LST; return as a monadic value the first
  452. value for which MPROC returns a true monadic value or #f. For example:
  453. (anym %state-monad (lift1 odd? %state-monad) '(0 1 2))
  454. => #t ;monadic
  455. "
  456. (with-monad monad
  457. (let loop ((lst lst))
  458. (match lst
  459. (()
  460. (return #f))
  461. ((head . tail)
  462. (>>= (mproc head)
  463. (lambda (result)
  464. (if result
  465. (return result)
  466. (loop tail)))))))))
  467. (define-syntax listm
  468. (lambda (s)
  469. "Return a monadic list in MONAD from the monadic values MVAL."
  470. (syntax-case s ()
  471. ((_ monad mval ...)
  472. (with-syntax (((val ...) (generate-temporaries #'(mval ...))))
  473. #'(mlet monad ((val mval) ...)
  474. (return (list val ...))))))))
  475. ;;;
  476. ;;; Identity monad.
  477. ;;;
  478. (define-inlinable (identity-return value)
  479. value)
  480. (define-inlinable (identity-bind mvalue mproc)
  481. (mproc mvalue))
  482. (define-monad %identity-monad
  483. (bind identity-bind)
  484. (return identity-return))
  485. ;;;
  486. ;;; State monad.
  487. ;;;
  488. (define-inlinable (state-return value)
  489. (lambda (state)
  490. (values value state)))
  491. (define-inlinable (state-bind mvalue mproc)
  492. "Bind MVALUE, a value in the state monad, and pass it to MPROC."
  493. (lambda (state)
  494. (call-with-values
  495. (lambda ()
  496. (mvalue state))
  497. (lambda (value state)
  498. ;; Note: as of Guile 2.0.11, declaring a variable to hold the result
  499. ;; of (mproc value) prevents a bit of unfolding/inlining.
  500. ((mproc value) state)))))
  501. (define-monad %state-monad
  502. (bind state-bind)
  503. (return state-return))
  504. (define* (run-with-state mval #:optional (state '()))
  505. "Run monadic value MVAL starting with STATE as the initial state. Return
  506. two values: the resulting value, and the resulting state."
  507. (mval state))
  508. (define-inlinable (current-state)
  509. "Return the current state as a monadic value."
  510. (lambda (state)
  511. (values state state)))
  512. (define-inlinable (set-current-state value)
  513. "Set the current state to VALUE and return the previous state as a monadic
  514. value."
  515. (lambda (state)
  516. (values state value)))
  517. (define (state-pop)
  518. "Pop a value from the current state and return it as a monadic value. The
  519. state is assumed to be a list."
  520. (lambda (state)
  521. (match state
  522. ((head . tail)
  523. (values head tail)))))
  524. (define (state-push value)
  525. "Push VALUE to the current state, which is assumed to be a list, and return
  526. the previous state as a monadic value."
  527. (lambda (state)
  528. (values state (cons value state))))
  529. ;;; monads.scm end here