monads.scm 20 KB

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