[ prog / sol / mona ]

prog


Monads,Async/Await : Algebraic Effects in C99

20 2021-01-14 14:43

>>16-18
This is not about random, it's just an example. And even then, the -DRND_VAL approach wouldn't work if you want to use the macro more than once. But comparing the macro directly doesn't even make sense to begin with, since C doesn't have list primitives.

The point of the example was to focus on the =(assert (symbolp list))=, a compile-time assertion about the kind of argument that was passed into the macro. >>19 doesn't fit that bill either, because it just generates code that does the checks at run-time.

And since I'm seeing that you're having so much fun with translating Lisp to C, here's one I recently had fun writing:

(defmacro roll (&body events)
  "Chance-based cond."
  (let* ((random (gensym))
	 (vars (loop for (chance . _) in events
		     collect (list (gensym) chance)))
	 (body (loop for (chance . action) in events
		     for (var . _) in vars
		     collect var into sum
		     collect
		     (cons (if (eq chance t) t
			       `(< ,random (+ ,@(copy-list sum))))
			   action))))
    `(let ((,random (random 1d0)) ,@vars)
       (declare (ignorable ,@(mapcar #'car vars)))
       (cond ,@body))))

which lets me write something like

(roll
  (0.3 'a)    ; return symbol a with a 30% chance
  (0.5 'b)    ; return symbol b with a 50% chance
  (t   'c))   ; return symbol c with a 20% (= 100% - 30% - 50%) chance

I'm looking forward to what you'll come up with, void.

69


VIP:

do not edit these