Ask Your Question
3

How to create an Applicative List in Haskell?

asked 2022-12-04 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-09-28 00:00:00 +0000

david gravatar image

An Applicative List in Haskell is a list that supports the Applicative Functor type class. Here's a way to create an Applicative List in Haskell:

instance Applicative [] where
  pure x = [x]
  fs <*> xs = [f x | f <- fs, x <- xs]

In this code, we define an instance of the Applicative type class for the List data type ([]). The pure function takes a value x and returns a list with that single value. The <*> operator takes a list of functions (fs) and a list of values (xs) and creates a new list by applying each function to each value in turn.

Here's an example of how to use this Applicative List:

ghci> [(+1), (*2)] <*> [1, 2, 3]
[2, 3, 4, 2, 4, 6]

The result is a list of all possible combinations of applying the functions to the values. In this case, we get [2, 3, 4, 2, 4, 6], which is equivalent to [(1+1), (2+1), (3+1), (12), (22), (3*2)].

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-04 11:00:00 +0000

Seen: 19 times

Last updated: Sep 28 '21