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

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.