1

Here is my attempt to implement Maybe monad in elisp. It it function composition that breaks on first nil. However value is always 13. Where is my error?

(defun .compose-maybe (&rest funcs)
  "Monad Maybe function composition with nil as Nothing."
  (lambda (arg)
    (if funcs
        (let ((value (funcall (apply #'.compose-maybe (cdr funcs)) arg)))
          (message "%s" value)
          (when value (funcall (car funcs) value))))
        arg))

(funcall (.compose-maybe (lambda (x) (* x 5)) (lambda (x) (+ 100 x))) 13)
4

1 回答 1

2

arg不在 的范围内(if funcs ...),因此 in 的内部 lambda.compose-maybe始终返回arg,而不是仅在funcsis时返回nil

(defun .compose-maybe (&rest funcs)
  "Monad Maybe function composition with nil as Nothing."
  (lambda (arg)
    (if funcs
        (let ((value (funcall (apply #'.compose-maybe (cdr funcs)) arg)))
          (message "%s" value)
          (when value (funcall (car funcs) value)))
      arg)))
于 2013-05-28T14:19:45.623 回答