I liked the walruses analogy! Gave me a good laugh.
If you don't mind my noob question, how would one iterate over an array/collection/vector, to create 100% immutable code? The usual loops would not be an option, as the iterator or counter variable needs to change.
The answer is: recursion. In true Functional Programming (which heavily features immutability), there are no loops. People throw around terms like "functional programming" and "immutability", but they rarely think about what it takes to fully implement these features.
Everything that you can do with a loop, you can also do with a recursive function. Here's a simple example:
That's a great question and thanks for asking. You're absolutely right about the iterator or counter variables changing. It's not something you can avoid really as it's so inherent to how loops work.
I don't have particular problem with that though (although in some languages you have to be careful, especially if writing asynchronous code that uses those variables). What's more important, in my opinion, is what you are doing in the iteration - are you mutating an array in place, or returning a new array? Using map and reduce where possible helps a lot.
I liked the walruses analogy! Gave me a good laugh.
If you don't mind my noob question, how would one iterate over an array/collection/vector, to create 100% immutable code? The usual loops would not be an option, as the iterator or counter variable needs to change.
The answer is: recursion. In true Functional Programming (which heavily features immutability), there are no loops. People throw around terms like "functional programming" and "immutability", but they rarely think about what it takes to fully implement these features.
Everything that you can do with a loop, you can also do with a recursive function. Here's a simple example:
Wow, thanks so much! This is exactly what I was looking for.
Hey, I'm glad you enjoyed the article <3.
That's a great question and thanks for asking. You're absolutely right about the iterator or counter variables changing. It's not something you can avoid really as it's so inherent to how loops work.
I don't have particular problem with that though (although in some languages you have to be careful, especially if writing asynchronous code that uses those variables). What's more important, in my opinion, is what you are doing in the iteration - are you mutating an array in place, or returning a new array? Using
map
andreduce
where possible helps a lot.Hope that helps!
I see - that question has bugged me a lot while I'm coding. Thanks for the advice!