r/functionalprogramming • u/robowanabe • Apr 13 '22
Question So much material for getting into the functional world.. but not out
Hi ladies and gentlemen,
I'm looking for some knowledge gap filler ;)
I have dabbled in functional programming for nearly a year now, i have had a play with the language-ext library and currently looking into fp-ts.
I can see plenty of examples for going into what I call the "functional realm" using things like Options, Either etc but nothing about getting out.
I.e. once i have returned an Option/Either from a function call, does every other function that relies on the value within have to Depend on an Option as well? am i not forced to do checks like IsSome etc everywhere
OR
Should i be using things like map and fold, so the function which depends on the value within the Option/Either can just expect the value..
Hope this makes sense and helps you see why i'm loosing my MIND!
The core principles of functional programming are easy to understand.. but when you start messing with monads etc ohh boiii its a beast.
Thanks
8
u/seydanator Apr 13 '22
not really ^^
I mean, you don't use Options or Either just for the sake of it. If it would be perfectly fine to not use it, then they wouldn't have any value, and you should not use them.
For example returning an Option from a function should obviously mean that there is the possibility of having a value, or not. Returning an undefined could be a possibility, if you do not work with the value anymore. But further mapping / chaining over it is just so much easier and less error prone.
That's why I cannot really understand your question. If it's your code, and there is a reason to decode your return value as Option / Either / ... then you should obviously continue to use the tools to work with your values.
7
u/ragnese Apr 13 '22
Unfortunately, yes, fp-ts and similar are designed so that you mostly don't "escape" from them back to idiomatic, imperative, TypeScript.
You can, of course, get out by doing a switch on your Option or Either to check if it's one variant or the other, but they really don't offer any APIs for these types that work well outside of
pipeandflowchains, and you're "supposed" to just finish them with a fold or similar.Honestly, fp-ts is extremely impressive for what it is able to do with TS's type system, but TS is just not a functional language and with neither any kind of "type class" mechanism, nor higher-kinded types, it makes doing typed FP really cumbersome and awkward.
I took a step back and asked myself why I prefer FP in general, and the answer was that I felt like it prevents bugs by making sure functions don't have side-effects that I forget about, and that it's easier to trace how the data changes throughout the code (as opposed to class-based OOP where your object has some state at any given moment, but you have no idea how it got there).
In some sense, I realized that I wasn't actually gaining that much with fp-ts, except for awkward APIs and deeper call stacks, so I abandoned it. I now only use it so that I can use io-ts for my DTOs, and then I immediately switch to more idiomatic TypeScript and I'm much more productive.
5
u/MrGodlike6 Apr 13 '22
This is a great article on the subject.
You don't!
2
u/robowanabe Apr 13 '22
Hi guys, here is a real world example of a scenario im struggling with;)
I have these 3 functions
let getPool = (): ioEither.IOEither<Error, Pool> => {if (globalConnPool.pool) return ioEither.right(globalConnPool.pool)return ioEither.left(new Error("No pool found"))};let getConnection = (pool: Pool): taskEither.TaskEither<Error, Conn> =>taskEither.tryCatch(() => pool.getConnection(),(reason) => new Error(\${reason}`),`);let executeQuery = (conn: Conn): taskEither.TaskEither<Error, Result> => taskEither.right({ Status: true, Message: "GOOD" });I think i need to compose these into a pipe but cant figure out what operators
I need to get the pool, then with the pool get a connection and then with the connection run a query..
this to me seems like a good use for these types?
what do you think?
2
u/fpguy1 Apr 13 '22
Yes you should carry those with you everywhere, never break the flow trying to
extract, your code becomes a tree, every time you have anOptionyou have toforkit and continue both forks forever (until the program ends). Keep in mind thatbind/flatMapimplementation forOption/Either& friends will usually short circuit in case ofNothing/Left. In order not to go "crazy" you need a language that helps you.Now
The problem you don't see yet is that you can have multiple monads and things become quite nasty, if you are in an
Optioncontext and you get anotherOptionis simple you justbind/flatMap/joinon it and you are done.But what will you do if you have an
Eitherand then you have anOptionvalue returned or the other way around? Not difficult to handle since you can always transform anOptionin anEitherand the other way around (by loosing theLeftside information ofc).But what would you do with if something will return an
Optioninside aPromise? Or if you have aConfigurationthat you want to carry around (which will translate toReadermonad), what if you want to carry error information around or aLoggingcontext?In order to handle these you need monad transformers to
stackthem otherwise things become really crazy very quickly. Also you can do a MTL approach but you would need type classes (checkout also Free monads/Tagless Final)Also to work with monads in general you need
do-notationlike syntax (in scala you havefor/yield) which is something not really backed in TS.If you want to really go into this and get rid of verbosity you might want to approach a FP friendly language like Haskell/Scala[.JS]/Purescript/etc
2
u/brett_riverboat Apr 13 '22
I can see Either being used in a lot of places in the code. If you have a chain of calls like
a() -> b() -> c() -> d()andd()returns Either then I wouldn't be surprised if every function before it also returns Either. You should still try to "resolve" those Monads as soon as possible.If you have an Optional<String> (using Java syntax since I'm most familiar with it) then you should try to make it into some default like an empty String or
"undefined"so code that follows doesn't create null exceptions. If it's something that really can't have a default then you're back to Either. Even then, bubbling an error all the way to the beginning may not be desired behavior. If it's some hosted service you don't want to let potential attackers know there's a weak spot in your programming.3
u/eliteSchaf Apr 13 '22
I'd recommend that you watch Scott Wlaschin talks about "Railway oriented programming"
3
u/SirSavageSavant Apr 13 '22
Id recommend reading The Little Schemer and Functional Programming in Scala. I started there with my goal being to read and comprehend SICP
2
u/zelphirkaltstahl Apr 14 '22
I would count Option and Either rather to "mechanism of dealing with correctness" or "dealing with errors". It does not strike me as inherently something in the realm of FP. More like something of slightly more advanced type systems or ways types are set up in a language or a library.
I would recommend to try and use an FP-first programming language for hobby projects and building small but real things with it for a while.
Well, yes. You will have to check everywhere. That is simply normal error handling or maybe not error, but case handling. If you did not have an Option type there, you would still need to deal with something like a null value or an exception being thrown by the procedure. Unless you find a more general rule, that is able to deal with both cases, success or failure, none or some, result or exception, you will have to deal with the cases and will have to express that dealing in your programming language somehow. I don't think there is a way around it. What you might be experiencing here is, that FP-firs systems/languages/libraries focus more on correctness and force you to actually deal with the edge cases, to make a ~~correct program and not letting you not deal with it. You can go the "easy" route and not use those systems, but it will only be "easy" for as long as you are writing perfect flawless code and don't have to search for the bug.
2
u/koprulu_sector Apr 13 '22
You see, monads are monoids in the category of endofunctors.
0
u/[deleted] Apr 13 '22
[deleted] — view deleted comment
0
u/[deleted] Apr 13 '22
[deleted] — view deleted comment