Haskell Applicative Lists
Applicative lists try every pairing of a wrapped function with a wrapped value. The result lists every combination in function order and then in value order.
Every pairing appears in order
Each number in the first list adds to each number in the second list. The order follows the first list and then the second list.
main :: IO ()
main = do
print ((+) <$> [1,2] <*> [10,20])A list can hold more than one function
A list can hold more than one function. Each function runs on every value in turn.
main :: IO ()
main = do
print ([(+1), (*10)] <*> [1,2])An empty list gives an empty result
An empty list ends the pairing at once. No function or no value means no result entries.
main :: IO ()
main = do
print ((*) <$> [2,3] <*> [])
print (([] :: [Int -> Int]) <*> [1,2])Example
main :: IO ()
main = do
print ((*) <$> [2,3] <*> [10,20])
print (length ((*) <$> [2,3] <*> [10,20]))Key points
- List apply: the operator <*> pairs every function in the first list with every value in the second list.
- Pairing order: functions stay in order and each function pairs with every value before the next function starts.
- List pure: pure wraps a plain value as a list with only that value in it.
- Empty list: an empty list on either side gives an empty result because no pairing is possible.
- Result size: the result holds one entry for every combination of a function and a value.
In this example, the first line multiplies every number in the first list by every number in the second list and the second line counts the four pairings.
Note
list apply is not zipping because it does not pair items by position alone.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What is (+) <$> [1,2] <*> [10,20]?