— CPSC 312 – 2021 – Lists in Haskell
module Lists where
— To run it, try:
— ghci
— :load Lists
— myappend l1 l2 returns the list containing the elements of l1 followed by the elements of l2
myappend [] l2 = l2
myappend (h:t) l2 = h : myappend t l2
— Try:
— myappend [1,2,3] [7,8,9]
— :type myappend
— myappend “fun” “ctional”
— ++++ is an infix form of append
[] ++++ l2 = l2
(h:t) ++++ l2 = h: (t ++++ l2)
— [1,2,3] ++++ [7,8,9]
— numeq x lst returns number of instances of x in list lst
numeq _ [] = 0
numeq x (h:t)
| h==x = 1 + numeq x t
| otherwise = numeq x t
— numeq 4 [7,1,4,5,4,6,7,4,8]
— numless x lst returns number of elements of list lst less than x
numless _ [] = 0
numless x (h:t)
| h
— pow2 n is true if n is a power of 2
pow2 1 = True
pow2 n
| n `mod` 2 == 0 = pow2 (n `div` 2)
| otherwise = False
— numc pow2 [1..1000000]
— myfilter c l returns list of elements of l for which c is true
myfilter c [] = []
myfilter c (h:t)
| c h = h : myfilter c t
| otherwise = myfilter c t
— myfilter pow2 [1..1000000]
— numc2 c lst returns number of instances of lst that have c true
numc2 c lst = length (myfilter c lst)
— numc2 pow2 [1..10000000]