Home > database >  Why aren't Drawn Values always used in List Comprehensions?
Why aren't Drawn Values always used in List Comprehensions?

Time:07-19

In Haskell, if I want to repeat a value I can write a list comprehension with the following form:

repeat_value x n = [x | _ <- [1..n]]

Why is it acceptable for me to use a generator that puts its values into a variable, _, that's never used?

CodePudding user response:

Syntactically, x <- gen is a repeated pattern-matching operation. For each value provided by the generator, it is matched against the pattern x, with whatever binding that might imply. For each pattern-match that succeeds, an expression is evaluated to produce a value to add to the list being built. For example, you could write [x | Just x <- [Just 1, Nothing, Just 2]] to get [1, 2].

In your example, you don't need to deconstruct the values with such a complicated pattern; you just need to produce them. You could match them against an irrefutable pattern like y, but y would not be used in the expression on the left, so why bind to a name? You can use the special irrefutable pattern _ instead.

  • Related