Skip to content

Commit 8bb7d80

Browse files
committed
Use 'pow' from #923
1 parent edc3055 commit 8bb7d80

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

examples/stdlib/stream/fastexp.effekt

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,20 @@ def fastexp(n: Int, k: Int) = product {
4343
}
4444

4545
def main() = {
46+
/// Computes n^exp for integers. (from #923!)
47+
def pow(n: Int, exp: Int): Int = {
48+
def go(n: Int, exp: Int, acc: Int): Int = {
49+
if (exp == 0) {
50+
acc
51+
} else if (mod(exp, 2) == 0) {
52+
go(n * n, exp / 2, acc)
53+
} else {
54+
go(n * n, exp / 2, acc * n)
55+
}
56+
}
57+
go(n, exp, 1)
58+
}
59+
4660
def prettyBits(bits: List[Bool]): String =
4761
"0b" ++ bits.map { b => if (b) "1" else "0"}.join("")
4862

@@ -63,7 +77,7 @@ def main() = {
6377

6478
def testExp(n: Int, k: Int) = {
6579
println(show(n) ++ " ^ " ++ show(k))
66-
println(n.toDouble.pow(k))
80+
println(n.pow(k))
6781
println(n.fastexp(k))
6882
}
6983

0 commit comments

Comments
 (0)