I am learning Haskell. One of the exercises I was asked to do was to compute all sums of a power set of a set of integers, e.g.:
allSums [1, 2, 5] -- should be [8,3,6,1,7,2,5,0]
I came up with this after reading about applicatives and functors, to which lists belong. It worked.
allSums :: [Int] -> [Int]
allSums [] = [0]
allSums (x:xs) =
if x == 0
then allSums xs
else (+) <$> [x, 0] <*> allSums xs
I was shook. It looks so terse, but it appears correct.
I do not know whom to talk to. My friends and parents think I am crazy.
How do you pronounce <$>
and <*>
? How do you even describe to people what they do?
When reading these to myself, I do not pronounce them; they are just a visual glyph in my mind. If I must speak them aloud, I would say "eff-map" for <$>
(possibly "eff-mapped onto" if there's some ambiguity) and "app" for <*>
(possibly "applied to" if there's ambiguity), which come from the pre-Applicative
names fmap
and ap
.
Also, I hate saying fmap
out loud. For this reason and others, I would likely mentally transform this to
pure (+) <*> [x,0] <*> allSums xs
before I said it so that I only need to pronounce pure
and (<*>)
. As an aside, I actually find it a little bit surprising that this style is not more common; especially when spreading applicative arguments across multiple lines, this is more uniform, as
pure f
<*> a
<*> b
<*> c
doesn't need to treat the a
line specially.