
Show HN: FunctionKit – Approachable functional concepts brought to Swift - mpangburn
https://github.com/mpangburn/FunctionKit
======
DavidPiper
Just reading the README.md makes me feel like I've leveled up my understanding
of functional concepts, well done!

That said, pardon my ignorance on the subject -

> This seems nice, but we've introduced an inefficiency: in mapping over the
> array twice, we unnecessarily create an intermediate array.

Isn't this an optimisation that could/should be handled by the compiler (JIT
evaluation or something like that)?

~~~
ilikebits
We call this type of optimisation "stream fusion".

In an ideal world, the compiler would always know to do this for us. In
practice, it's very difficult (in most languages) to determine whether this
optimisation is correct.

In the README example's case, the optimisation happens to be correct because
both mapping functions are pure. If they had side effects, then stream fusion
might create different results than the original code. Let's make this
concrete with an example.

Say our array is `[1, 2]` and our functions are `function A(n) { print("A:
"+n) }` and `function B(n) { print("B: "+n) }`. Then _without_ stream fusion,
we would see the following output: ``` A: 1 A: 2 B: 1 B: 2 ```

_With_ stream fusion, we would see different output: ``` A: 1 B: 1 A: 2 B: 2
```

Since the mapping functions have side effects, stream fusion is not valid
here.

Some languages can do automatic implicit stream fusion. Haskell is a great
example of this: it's able to determine when stream fusion is correct because
the language has an _effect tracking system_ where functions with side effects
are distinct from functions without side effects.

~~~
wereHamster
> In practice, it's very difficult (in most languages) to determine whether
> this optimisation is correct. > > [...] the optimisation happens to be
> correct because both mapping functions are pure. If they had side effects,
> [...]

TLDR: make all your functions pure. It'll make it so much simpler for you,
your coworkers, but also the compiler(!) to reason about your code.

About half of the bugs and issues I come across in my $DAYJOB are because code
that I use (through a third-party library) is not pure. If I had a penny every
time I fixed a bug caused by impure code, I'd be rich.

~~~
jsjohnst
> If I had a penny every time I fixed a bug caused by impure code, I'd be
> rich.

Ok, let’s be extremely optimistic and say you fix 25 functional purity bugs a
day and you’ve been fixing impure code for twenty years.

$0.01/bug * 25 bugs/day * 250 working days/year * 20 years = $1,250.

I guess that $1,250 could be rich to some, but I do think making a quarter per
full day of fixing bugs doesn’t seem like a great way to get there.

------
tekstar
This would likely pair well with this functional interface to uitableview.

[https://github.com/Shopify/FunctionalTableData](https://github.com/Shopify/FunctionalTableData)

