Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are list comprehensions implemented in Haskell?

  • Are list comprehensions simply a language feature?
  • What's the easiest way to fake a list comprehension using pure Haskell?
  • Do you have to use a do block/>>= to do this or could you use some other method for hacking a list comprehension together?

Clarification: By "fake" a list comprehension I mean create a function that takes the same input and produces the same input, i.e. a form for the return values, lists to crunch together, and a predicate or multiple predicates.

like image 409
reem Avatar asked Dec 19 '13 17:12

reem


People also ask

How do list comprehensions work in Haskell?

List comprehension in Haskell is a way to produce the list of new elements from the generator we have passed inside it. Also for the generator values, we can apply the Haskell functions to modify it later. This list comprehension is very y easy to use and handle for developers and beginners as well.

How do list comprehensions work?

List comprehensions provide us with a simple way to create a list based on some sequence or another list that we can loop over. In python terminology, anything that we can loop over is called iterable. At its most basic level, list comprehension is a syntactic construct for creating lists from existing lists.

How do I display lists in Haskell?

Example #1print("Demo to show list in Haskell !!") let list1 = [100, 50, 235, 167, 345, 909, 675, 20] let list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9] let list3 = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6] let list4 = [5, 10, 15, 20, 15, 30, 35, 40] let list5 = [123.4, 567.9, 56.0, 3.9, 76.9] print("printing list element !!")


2 Answers

Section 3.11 in the Haskell report describes exactly what list comprehensions mean, and how to translate them away.

If you want monad comprehensions you basically need to replace [e] by return e, [] by mzero, and concatMap by (>>=) in the translation.

like image 130
augustss Avatar answered Oct 30 '22 11:10

augustss


To augment augustss's answer, if you have something like:

[(x, y) | x <- [1..3], y <- [1..3], x + y == 4]

... it is equivalent to this use of do notation:

do x <- [1..3]
   y <- [1..3]
   guard (x + y == 4)
   return (x, y)

... which is equivalent to this use of concatMap:

concatMap (\x ->
    concatMap (\y ->
        if (x + y == 4) then [(x, y)] else []
        ) [1..3]
    ) [1..3]
like image 24
Gabriella Gonzalez Avatar answered Oct 30 '22 13:10

Gabriella Gonzalez