⚡Eineygður ☯ Flakkari⚡ on Nostr: So, I'm open to critique on this if either of you (or any other Elixers) feel up for ...
So, I'm open to critique on this if either of you (or any other Elixers) feel up for it. This is part of the algorithm I mentioned for determining AKS primality which calculates coefficients based on Pascal's triangle. Below is the Elixir code followed by equivalent JavaScript for comparison. The Elixir seems to do what I wanted, but by Gods is it ever ugly and convoluted. FYI, I'm using a map instead of a list in Elixir because it's easier to access map values with their numeric key than list elements by their index.
---[ coef.ex ]---
defmodule X do
def coef(n), do: Enum.reduce(0..(n - 1), %{0 => -1},
fn i, coef -> Map.put(coef, 0, -coef[0]) |> Map.put(i + 1, 1)
|> (& Enum.reduce_while(0..i, { i, &1 }, fn _, {j, c} ->
j == 0 && { :halt, c }
|| { :cont, { j - 1, Map.put(c, j, c[j - 1] - c[j]) } }
end) ).()
end) |> (& Map.put(&1, 0, -&1[0]) ).()
end
[n | _?] = System.argv
Integer.parse(n) |> elem(0) |> X.coef |> IO.inspect
---[ coef.js ]---
function coef(n) {
const c = []
c[0] = 1;
for (let i = 0; i < n; c[0] = -c[0], i++) {
c[1 + i] = 1;
for (let j = i; j > 0; j--) c[j] = c[j - 1] - c[j];
}
return c;
}
console.log(coef(process.argv[2]))
---[ coef.ex ]---
defmodule X do
def coef(n), do: Enum.reduce(0..(n - 1), %{0 => -1},
fn i, coef -> Map.put(coef, 0, -coef[0]) |> Map.put(i + 1, 1)
|> (& Enum.reduce_while(0..i, { i, &1 }, fn _, {j, c} ->
j == 0 && { :halt, c }
|| { :cont, { j - 1, Map.put(c, j, c[j - 1] - c[j]) } }
end) ).()
end) |> (& Map.put(&1, 0, -&1[0]) ).()
end
[n | _?] = System.argv
Integer.parse(n) |> elem(0) |> X.coef |> IO.inspect
---[ coef.js ]---
function coef(n) {
const c = []
c[0] = 1;
for (let i = 0; i < n; c[0] = -c[0], i++) {
c[1 + i] = 1;
for (let j = i; j > 0; j--) c[j] = c[j - 1] - c[j];
}
return c;
}
console.log(coef(process.argv[2]))