r/functionalprogramming • u/ACrossingTroll • Dec 26 '23
Question Deeply nested exceptions
Hi, I'm currently learning FP and many concepts I see I have actually already implemented myself in OOP. One thing though is still a bit fuzzy to me, and that's error handling.
Let's say I want to parse some (string) and either it's valid and returns the parsed value (int) or it returns an error (string). As I understand it, with FP you would use EITHER, with the left (error) and right (happy) path. Afterwards you can nest the error path vs happy path with FLATMAP, effectively passing through the error, or continuing the program flow. So far so good, I hope.
Now my concern is: what if your error check happened 30 levels down the stack? Wouldn't that mean you constantly have to FLATMAP until you finally deal with the error on level 5 etc, like printing it? Also doesn't that mean you pretty much would end up flatmapping your functions all the time because error handling is everywhere? Like writing a "flatmappedfunction" you'd use all over the place?
This is where OOP seems to be much easier. I know it is obfuscating the program flow a bit. But you just would need to throw the exception once and deal at the appropriate place up in the stack. Instead of 30x FLATMAP?
Please correct me if I'm wrong.
View all comments
Show parent comment
6
u/RedGlow82 Dec 26 '23
The reason why such syntactic sugar was added in languages like Haskell was, between various reasons, to handle the kind of problems you found. Languages like JavaScript didn't have to handle these problems, because they had other constructs, like exceptions, so you don't have the necessary instruments to handle the errors in the way you want to. You should use languages according to their idiomatic uses. If you don't, you will encounter stopblocks and annoying patterns like the one you faced, and often times there's no way around it. Languages like JavaScript, PHP or Python do support a limited amount of useful FP constructs, but don't have enough support to practically adopt others (like monadic errors).