3 ms·
A cliche example is "squares of values". imperative code would be something like: fn squares(array A) array B; for (idx, x) in A { B[idx] = x
by rgoulter 8y ago
A cliche example is "squares of values".
imperative code would be something like:
fn squares(array A)
array B;
for (idx, x) in A {
B[idx] = x * x
}
return B;
}
(or "B.add" or some other mutating action).
whereas 'declarative' code 'declares' what it wants:
fn squares(array A) {
return A.map { |x| x * x }
}
I think "declarative" is used more in terms of "declare the result you want, not how you'll get it". It's easier to focus on what the output of the program is with declarative code.
Higher-level abstractions are probably necessary, but I don't think it's fundamental to how I'd use the term.
:-) Although I wouldn't be surprised to see a variety of ways people use the term.
- jtms 8y agoIs that example code elixir?
- rgoulter 8y agoIt's not anything in particular. Rosetta Code has "apply a callback to an array" example with Elixir. https://rosettacode.org/wiki/Apply_a_callback_to_an_array#Elixir https://rosettacode.org/wiki/Apply_a_callback_to_an_array#El... Enum.map([1, 2, 3], fn(n) -> n * 2 end) Enum.map [1, 2, 3], &(&1 * 2)