Haskell 3

Propose:

Notes.lhs has codes presented in these notes as well as other examples.


List comprehension

Example

> [x | (x:xs)<-[[3],[1,2],[],[4,5,6],[],[10]]]
[3,1,4,10]
   ( Reference: Use web.archive.org to find the archived pages
       from FOLDOC 
       and the Haskell Companion )


Two-line wonders

How does this work?

Mersenne primes

List examples

Permutations


List module

Using a function in List

Member


  Fibonacci:

> factseq = 1 : 1 : [ f | f <- zipWith (*) (tail factseq) [2 ..] ]
> factseq = 1 : 1 : zipWith (*) (tail factseq) [2 ..]
> fibSeq2   = 1 : 1 : [ x+y | (x,y) <- zip fibSeq2 (tail fibSeq2) ]
> fibSeq3   = 1 : 1 : [ x+y | x <- fibSeq3 | y<- (tail fibSeq3)]

  gcd (fib !! m) (fib !! n) == fib !! (gcd m n)

One Last Neat example: Quicksort using list comprehension

> quicksort  []     =  []
> quicksort (x:xs)  =  quicksort [y | y <- xs, y<x ]
                     ++ [x]
                     ++ quicksort [y | y <- xs, y>=x]



Python

Lazy evaluation:
def iteratorC():
    yield 1
    yield 2
    yield 3
 
def fib():
     fn2 = 1 
     fn1 = 1 
     while True:
           (fn1,fn2,oldfn2) = (fn1+fn2,fn1,fn2)
          yield oldfn2
class fibnum:
      def __init__(self):
         self.fn2 = 1 # "f_{n-2}"
         self.fn1 = 1 # "f_{n-1}"
      def next(self):
         (self.fn1,self.fn2,oldfn2) = (self.fn1+self.fn2,self.fn1,self.fn2)
         return oldfn2
      def __iter__(self):
         return self

List comprehension:
...> s = [x**2 for x in range(10)]
...> s
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
...> [x for x in s if x % 2 == 0]
     [0, 4, 16, 36, 64]

def iteratorC():
    yield 1
    yield 2
    yield 3


...> [x for x in iteratorC()]
[1,2,3]

PythonVsHaskell
Python Cookbook -- Constructing Lists with List Comprehensions

Note:  Ther term conprehension comes from the axiom of comprehension in set theory, which makes precise the idea of constructing a set by selecting all values that satisfy a particular property. (Pg 56: Programming in Haskell by Graham Hutton, 2016)