Clarify the role of the list monad operator

I came across a Haskell function that tells you if a list is sorted, and it's hard for me to figure out how this works.

The code in question

f = zipWith (<=) <*> tail 

which, as I understand it, is equivalent (in exact style) to

 f' xs = zipWith (<=) xs (tail xs) 

and as an example returns

 f [4, 5, 1] == [True,False] 

I suppose this has something to do with the monad list and sequential application, but it would be appreciated if someone could make the meaning more clear to me. What does <*> do here?

+6
source share
2 answers

<*> here does not affect the applicator [a] acting on the applicative instance (->) a .

Essentially

  instance Applicative ((->) a) where pure = const -- same as monadic return f <*> a = \x -> fx (ax) 

Thus, it acts as a function application, but also wraps the application in a function and gives an argument to both sides.

So, expanding your function

  zipWith (<=) <*> tail \x -> zipWith (<=) x (tail x) \(x:xs) -> zipWith (<=) (x:xs) xs 

In general, it’s right to see <*> how simple the application-application + additional additional properties. You can almost read it as a space!

+12
source

<*> actually from (->) a as an applicative functor. This is an S-combinator that distributes the argument (list xs in your extension) to two functions ( zipWith (<=) and tail ) in the way you specified in the extension: (f <*> g) x = fx (gx) .

To understand this, you need to check the type (<*>) . Since both of his arguments are a->b , we are talking about a->b as an Applicative Functor - not a List.

+7
source

Source: https://habr.com/ru/post/970099/


All Articles