Exponentiation operator: Difference between revisions
Content added Content deleted
m (→{{header|OCaml}}: generic pow) |
|||
Line 649: | Line 649: | ||
# 2.4 **. 3 ;; |
# 2.4 **. 3 ;; |
||
- : float = 13.824</lang> |
- : float = 13.824</lang> |
||
It is possible to create a generic exponential. For this, one must know the |
|||
multiplication function, and the unit value. Here, the usual fast algorithm is |
|||
used. |
|||
<lang ocaml>let pow one mul a n = let rec g p x = function 0 -> x | i -> |
|||
g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2) in g a one n;; |
|||
pow 1 ( * ) 2 16;; (* 65536 *) |
|||
pow 1.0 ( *. ) 2.0 16;; (* 65536. *) |
|||
(* pow is not limited to exponentiation *) |
|||
pow 0 ( + ) 2 16;; (* 32 *) |
|||
pow "" ( ^ ) "abc " 10;; (* "abc abc abc abc abc abc abc abc abc abc " *) |
|||
</lang> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
<lang Perl>#!/usr/bin/perl -w |
<lang Perl>#!/usr/bin/perl -w |