Pergunta

Let's say we have this point-free function:

f1 = flip const map

I'm clueless about how exactly does it work and what it is supposed to do? I.e. I know what map, const and flip functions are. But putting them together like this just doesn't make sense to me. What exactly is happening inside this function? It seems to return the same thing I pass into it every time but... Why?

Foi útil?

Solução 2

Keep in mind that all functions in Haskell take only one argument but simulate taking multiple arguments by returning another function. So flip const map can also be written as (flip const) map. const normally ignores its second argument and returns its first argument. flip reverses the order of the arguments, so flip const ignores the first argument and returns the second argument. So map gets ignored and a function is returned that always returns its argument.

Outras dicas

Let's see what this function does, bit by bit

flip const map x = (flip const) map x
                 = const x map
                 = x

That's why it always returns what you give it!

It really doesn't matter if you put something other than map in there. The expression flip const flips the arguments of const, so instead of always returning its first argument, it returns its second. You can test this by redefining f1 = flip const undefined. This will result in an exception if undefined is ever evaluated, but you can see that it gives the same behavior. Essentially, flip const undefined = id.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top