r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

Show parent comments

96

u/Servious Apr 05 '22 edited Apr 06 '22

IMO these things are best understood through the lens of Haskell's Maybe type.

Very simply, a Maybe Int for example can be either Just 5 or Nothing. At its most basic form, it can be used with pattern matching. For example here's a haskell function that adds 2 to a Maybe if it's there:

add2 :: Maybe Int -> Maybe Int
add2 (Just n) = Just (n + 2)
add2 Nothing = Nothing

You can see we had to use pattern matching to "unwrap" the actual value of the maybe so we could add 2 to it. This is pretty inconvenient and pretty annoying especially if you're trying to do something more complex than simply adding 2. That's where Functor comes in.

Functor allows you to apply a function to the value inside the functor and get back the modified functor by using the fmap function. Here's what that definition looks like:

fmap :: Functor f => (a -> b) -> f a -> f b

This definition is a bit complex so I'll break it down. This is saying "fmap is a function which is defined for any Functor f. This function accepts a different function from a to b; and a functor containing an a; and returns a functor containing a b." a and b can be any type. What makes something a functor at the very base level is whether or not this function is defined. You can think about it like mapping over a list in any other language because that's exactly what fmap is defined as for lists.

So in our Maybe example, we can use it like so:

add2 :: Maybe Int -> Maybe Int
add2 x = fmap (+ 2) x
-- or
add2 x = (+ 2) <$> x -- <$> is just an infix version of fmap; same exact function.

Much more convenient, and as an added bonus it looks a bit more like regular function application (in haskell anyway).

We're not quite to monads yet because there's a step between Functor and Monad and that's called Applicative. Instead of starting with the (somewhat confusing) definition, let me pose a question: what if I have a function with more than one argument that I want to pass Maybes into? Like what if I wanted to add two Maybe values together? That's the problem applicative solves.

With functors we can do:

(+ 2) <$> x

But with an applicative instance we can do:

(+) <$> maybeA <*> maybeB

the result of which will be a Maybe containing the result of adding the two values inside. If either of the Maybe values are Nothing it will come out as Nothing. And this pattern is extendable for more than just two arguments as well. For example:

functionWithManyNonMaybeArguments <$> maybeA <*> maybeB <*> maybeC <*> maybeD

So to quickly summarize: functors allow you to apply a function to the inside of one "wrapped" value (like Maybe). Applicatives allow you to apply a function of many arguments to many "wrapped" values. Now, here's where we get to monads. Here's a situation you might be in:

someFn :: a -> Maybe c
someMaybe :: Maybe a

How would you feed that someMaybe value into the someFn function? You might guess to use fmap from functor, but let's look at what would happen:

fmap someFn someMaybe
fmap :: Functor f => (a -> b) -> f a -> f b
-- so in this case
fmap :: Functor Maybe => (a -> Maybe c) -> Maybe a -> Maybe (Maybe c)
-- so
fmap someFn someMaybe :: Maybe (Maybe c)

Oof, double-wrapped Maybe; That's not right. This is the problem Monad solves with the bind function or >>= operator. The correct code for this would be:

bind :: Monad m => m a -> (a -> m b) -> m b -- again, >>= is just an infix version of bind; exact same thing.
someMaybe >>= someFn :: Maybe c

Also worth noting that for something to be a Monad it must also be Applicative and for something to be Applicative it must also be a Functor. So all monads are also applicatives and functors.

Sorry if you don't know any Haskell because this is pretty complex and very haskell-focused, but I kinda figured you wouldn't be asking these questions without a passing familiarity with some haskell. Feel free to ask any questions; I love talking about this stuff!

19

u/teito_klien Apr 05 '22

This is by far one of the best explanations of functors, applicative and monads, I’ve ever read.

Thanks a lot !

17

u/FiveOhFive91 Apr 06 '22

This is by far the first explanation of functors, applicative and monads, I’ve ever read.

5

u/[deleted] Apr 05 '22 edited Apr 05 '22

This is a really clear explanation, so thank you for writing it. I hadn't understood fmap or bind at all before this, and I had seen them used a lot, but they ended up being a lot simpler than I anticipated. I still have a few questions though, and because you said questions are welcome, I'll ask:

I looked up the difference between (<$>) and (<*>), and it looks like this is the type signature difference (the top I just copied from your comment).

fmap :: Functor f => (a -> b) -> f a -> f b

(<*>) :: Functor f => f (a -> b) -> f a -> f b

Why is (<*>) an applicative and fmap a functor? Also, you said that fmap deals with monads like Maybe, but the type signature looks like it deals with functors applied to some type a and some type b. Am I misinterpreting it?

3

u/Servious Apr 06 '22 edited Apr 06 '22

What makes <*> associated with applicative (the function itself is not an applicative) is that it is defined in the Applicative typeclass in Haskell. (link) Same with fmap and Functor.

I think maybe what's happening here is if you haven't seen many typeclasses before this can be somewhat confusing. Essentially there exists a definition somewhere that says "hey if you want your type f (Maybe, for example) to "be" a Functor you need to implement the fmap function for it." In haskell that sentence looks like this:

class Functor f where
    fmap :: (a -> b) -> f a -> f b

For Maybe the instance looks like this:

instance Functor Maybe where
    fmap f (Just x) = Just (f x)
    fmap f Nothing = Nothing

If I were to lookup the type of fmap I would get the definition I gave before. You'll notice that in this typeclass definition, there is no Functor f => ... part in fmap's type. That's because f is already defined in the class Functor f portion of the typeclass declaration. Probably the same thing happened when you looked up the applicative operator; it didn't include that f needs to be Applicative in the function type because that's already included in the fact that it's the Applicative definition. I'm not wording this well but I hope it makes some sense. The definition for <*> includes Functor because applicatives need to be functors first. Every applicative is a functor.

And for the second half of your question I'll just break down what the whole function definition means.

(<*>) - the name of our function

Functor f => - This is not an argument to the function. It is saying "hey we're going to use this generic Functor type that could be anything that implements the Functor typeclass and we're going to call it f." Again, not an argument to the function. If you use Java you can think of it like the <T extends Functor> portion of a method declaration.

f (a -> b) - this is the first argument; it's saying we will take a function from a to b wrapped in a functor (very weird I know but I will elaborate later)

f a - this is the second argument; it's an a wrapped in the same functor as before.

and finally f b is the result of our function; a b wrapped in our functor f.

So the way this works is pretty interesting and complicated so I'll use a concrete example. Let's say we have a function

sum3 :: Int -> Int -> Int -> Int

Now if we wanted to use it with Maybes (Applicatives, because there is an Applicative instance for Maybe), we can do

sum3 <$> a <*> b <*> c

So let's break down how this works. First, sum3 <$> a. In this case, sum3 needs to fit into the (a -> b) format fmap expects. Because of currying, haskell does it like so:

a = Int
b = Int -> Int -> Int

So you can think of it like Int -> (Int -> Int -> Int). Because the result of fmap is always f b, our result will be Maybe (Int -> Int -> Int). Huh, a function wrapped in a functor. Sounds familiar right? This is where our Applicative instance comes in. When we use the applicative operator to do sum3 <$> a <*> b we now get

(<*>) :: Functor f => f (a -> b) -> f a -> f b
-- so in this instance
(<*>) :: Functor Maybe => Maybe (Int -> (Int -> Int)) -> Maybe Int -> Maybe (Int -> Int)
-- which means
a = Int
b = Int -> Int

So you can (hopefully) see how each time we continue to add arguments, the size of the function wrapped in a functor gets smaller and smaller until eventually it's just the final wrapped value.

I know this is a bit more than you asked for, but like I said I love talking about this stuff lmao. Again, feel free to ask questions. I feel like this comment wasn't as clear as my previous one and it was definitely more technical. And of course if I didn't really understand/answer your question and just rambled aimlessly PLEASE let me know lol

2

u/[deleted] Apr 06 '22 edited Apr 06 '22

No, this is actually great, haha. Thank you for your explanation, because it makes a lot of sense. I like how you broke down every single part of the function application, substituting the functions for the results each time; I think this is a really effective way to explain it and reason about it. That really helped focus on the type stuff (i.e. functors, applicative instances, monads), which is the part of Haskell I'm less familiar with. It's satisfying seeing how composable everything is, when you break it down like that (e.g. because (<*>) evaluates to an f b given an f a and an f (a -> b), with a function it returns an f (Int -> Int -> Int); it's simple, because that's literally how Haskell works, but it's interesting).

I think I get it now, and I have no more questions. Again, I definitely appreciate your explanation.

2

u/Servious Apr 06 '22 edited Apr 06 '22

Glad it helped! When I was learning about this stuff I got really, really tired of overly-abstract, wishy-washy explanations about "effects" and "wrapping" and "composability" so whenever I explain this kind of thing I like to start from a concrete, "what do I use this for when actually programming in Haskell" angle.

The complete beauty of this is exactly how flexible it is. Instead of Maybe you could do this with, for example, Either and have a whole exception-handling flow entirely handled almost implicitly. You can even write a totally monadic parsing library (long but so, so worth it! [and where I learned most of this stuff lol])

2

u/faceplanted Apr 05 '22

This was a really good explanation aside from that I couldn't read any of the syntax, I learned functional programming in Scala.

3

u/Servious Apr 06 '22

Maybe it's time to learn some Haskell! ;)

2

u/leftofzen Apr 06 '22

This explanation is probably great if you already know some Haskell. If you don't, this explanation is pretty useless.

1

u/Servious Apr 06 '22

Not really sure why someone would be wanting to know about those things without knowing a bit of Haskell or similar language first. They're pretty useless outside of that context.

1

u/shawntco Apr 06 '22

I come from a web dev background and know very little about Haskell. Your explanation lost me at Just 5. :D