r/functionalprogramming • u/aerdna69 • Nov 19 '23
Question How would you create a counter
Since I often read here that FP is really simple, it's just that our mind is wired in a wrong way, how would you simply create a counter dictionary / HashMap ?
3
Upvotes
6
u/bobsollish Nov 19 '23
RE: “… our mind is wired in a (sic) wrong way …”
Nope. It’s just that it’s not the first programming (paradigm) that most people learn.
5
u/delfV Nov 19 '23
Not sure if this is what you mean, but:
(def counter {:a 1, :b 3})because in FP data and functions to manipulate them are separated. If you want to increase it then
(update counter :a inc)4
u/proofconstruct Nov 19 '23
Not sure if this is a trolling post, but in case it’s sincere, there are several formulations of this idea used all over. Here’s one way in Haskell: https://hackage.haskell.org/package/hashmap-1.3.3/docs/Data-HashMap.html, and this one (also Haskell) is conceptually probably the simplest you can find: https://hackage.haskell.org/package/assoc-list
2
u/[deleted] Dec 21 '23
The trouble with FP is when you're new to it you have no concept. And trying to get some concept without doing the work makes no sense. I tried that and failed to undestand myself. It was only after I put in the work to learn one flavor of FP (Clojure's) I got it.
Of course, there's mutability! No one would suggest otherwise.
FP is about teasing the pure apart from the impure. That is all.
Don't try to understand FP by dipping your toe in the pool. Jump into the pool. I recommend you start with ClojureScript and create a web app.
3
u/[deleted] Nov 20 '23
You should look into Okasaki's Purely Functional Data Structures. It is a fascinating topic with lots of cool solutions.
2
u/mchwds Nov 19 '23 edited Nov 19 '23
In Elixir you’d most likely use a map. You can create one like this:
%{}
And if you want to count all the words in a sentence you can do so like this:
sentence |> String.split(“ “) |> Enum.frequencies()
https://hexdocs.pm/elixir/1.15.7/Enum.html#frequencies/1