Modular arithmetic: Difference between revisions

Line 620:
{{out}}
<pre>f(ModularInteger(10, 13)) = ModularInteger(1, 13)</pre>
 
=={{header|Common Lisp}}==
{{trans|Scheme}}
 
In Scheme all procedures are anonymous, and names such as <code>+</code> and <code>expt</code> are really the names of variables. Thus one can trivially redefine "functions" locally, by storing procedures in variables having the same names as the global ones. Common Lisp has functions with actual names, and which are not the contents of variables. There is no attempt below to copy the Scheme example's trickery with names. (Some less trivial method would be necessary.)
 
<syntaxhighlight lang="lisp">
(defvar *modulus* nil)
 
(defmacro define-enhanced-op (enhanced-op op)
`(defun ,enhanced-op (&rest args)
(if *modulus*
(mod (apply ,op args) *modulus*)
(apply ,op args))))
 
(define-enhanced-op enhanced+ '+)
(define-enhanced-op enhanced-expt 'expt)
 
(defun f (x)
(enhanced+ (enhanced-expt x 100) x 1))
 
;; Use f on regular integers.
(princ "No modulus: ")
(princ (f 10))
(terpri)
 
;; Use f on modular integers.
(let ((*modulus* 13))
(princ "modulus 13: ")
(princ (f 10))
(terpri))
</syntaxhighlight>
 
{{out}}
<pre>$ sbcl --script modular_arithmetic_task.lisp
No modulus: 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011
modulus 13: 1
</pre>
 
=={{header|D}}==
1,448

edits