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

133

u/shawntco Apr 05 '22

Wtf is a monad, functor, etc

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.

→ More replies (1)

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

33

u/WhoTouchaMySpagoot Apr 05 '22

There’s a vid on youtube by brian beckman. It’s called don’t fear the monad

21

u/[deleted] Apr 05 '22

I love your username, thanks for the laugh

0

u/[deleted] Apr 05 '22

[deleted]

0

u/[deleted] Apr 05 '22

[deleted]

1

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

here i think you need a relaxed definition of a monoid

edit: found it https://en.wikipedia.org/wiki/Monoid_(category_theory)

→ More replies (5)

5

u/ExtraFig6 Apr 05 '22 edited Apr 05 '22

Start with functor.

If you tell me programming languages you're familiar with i can give you code examples

If you've used a function like map or for each, you've probably used functors.

A functor has two parts. It does something to types, and it does something to functions between those types.

For example, list. What does list do to types? It gives you a new type called list of ___. So

int           => list<int>
string     => list<string>
list<int> => list<list<int>>

Now what about functions? Well, you can map functions across a list. So if you have a function

 f : A -> B

You can map it

 list-map(f) : list<A> => list<B>

By doing f to each element in the list, returning the result.

Optional/maybe/nullable is also a functor. You can think of it as being a list that can only have 0 or 1 element.

What does map do? If you've used an Elvis operator, it's like that. If the input is null, just return null. Otherwise, do the function.

1

u/shawntco Apr 06 '22

I'm a web developer, most Haskell and the like goes right over my head

→ More replies (2)

2

u/DrewTheVillan Apr 05 '22

Functors are absolutely beautiful. Very clever design

1

u/ExtraFig6 Apr 06 '22

I think they originally came from algebraic topology

2

u/[deleted] Apr 05 '22

Idk but I know what a gonad is

1

u/ExtraFig6 Apr 07 '22 edited Apr 07 '22

Functors, typescript version!

Intro/example

You already use functors. It's helpful to think of them as a design pattern instead of a construct inside of a programming language.

Roughly, a functor is something you can map across. For example, an array.

let square : (x: number) => number 
  = (square = x => x*x);

We can map this across an array of numbers:

let some_numbers : Array<number> = [1,2,3,4,5];
let some_squares = some_numbers.map(square);

In other words, we can take a function with type

 (x: number) => number

and make a function

let square_array : (xs: Array<number>) => Array<number>
  = (xs => xs.map(square));

We can of course do this for any function. Here's a generic function that captures this process:

let array_map<In,Out>: 
    ((x: In)         => Out) 
    => 
    ((xs: Array<In>) => Array<Out>)
 = (f => 
     (xs => xs.map(f)));

Which we can use like this:

let square_array = array_map(square);
square_array([1,2,3]) // => [1,4,9]

Definition:

A functor has two parts. The first is a type function, aka a function that takes types and return types. Let's call it F for now. In typescript, this usually takes the form of a generic class. In the example above, the type function was Array.

The second is a higher order function (map) that takes functions of type

(x: In) => Out

and turns them into functions of type

(x: F<In>) => F<Out>.

F turned the types In and Out into other types. map brings the along the functions.

There's one requirement on map: it must preserve composition of functions. More explicitly,

map(compose(f,g)) 

must be equivalent to

compose(map(f), map(g)). 

To go back to the Array example, consider the functions

// this will be our g
let inc : ((x: number) => number) 
  = (x => x + 1);

// this will be our f
let square : ((x: number) => number) 
  = (x => x*x);

If we want to add 1 then square every element in the list, it shouldn't matter if we do this in one pass or do it in two (first add 1, then square):

xs => array_map(x => square(inc(x)))(xs)

is equivalent to

xs => array_map(square)(array_map(inc)(xs))

Most programming languages don't have a way to enforce this requirement. But if map didn't satisfy this property, I think most people would be surprised (even if they haven't studied functors).

You can visualize this requirement with a diagram:

A ----------g----------> B
 _                      |
    _                   f
  compose(f,g)           |
            _           V
                \----->  C

F<A> -------map(g)----> F<B> 
   _                    |
      _                map(f)
   map(compose(f,g))     |
            _           V
                \---->  F<C>

and saying both paths from F<A> to F<C> must be equivalent.

Why

Functors (like much of category theory) originated in algebraic topology. Mathematicians wanted to study functions between topological spaces by comparing them to functions between algebraic objects, which were better understood. This substitution works provided you don't break function composition.

But in programming, we use these for different reasons. We have lots of types that are built up from other types, like Array<T>, Option<T>, Future<T>, and it's useful to have a way to build up corresponding functions.

Any time you have one of these, you probably end up using functors. If not intentionally, then in an ad-hoc way. If you have seen code that's constantly checking if null, that is a spaghetti code implementation of the Optional functor.