CS计算机代考程序代写 Haskell — CPSC 312 – 2021 – Lists in Haskell

— CPSC 312 – 2021 – Lists in Haskell
— A redefinition of some of the predefined list definitions (with new names)

module Lists2 where

— To run it, try:
— ghci
— :load Lists2

— myelem e l is true iff e is an element of list l
myelem _ [] = False
myelem e (h:t)
| e==h = True
| otherwise = myelem e t

— mytake n l returns first n elements of list l
mytake :: Int -> [t] -> [t]
mytake 0 _ = []
mytake _ [] = []
mytake n (x:xs) = x:mytake (n-1) xs

— mytake 20 [1..]

myhead (h:_) = h
mytail (_:t) = t
— myhead [1,2,3,4]
— mytail [1,2,3,4]
— myhead “abcd”
— mytail “abcd”
— mytail “a”
— mytail “”

— lst !!! n returns n’th element of lst (My implementation of !!)
(h:_) !!! 0 = h
(_:t) !!! n = t !!! (n-1)

— [1..] !!! 33

— lst1 +++ lst2 returns lst containing elements of lst1 followed by elements of lst2
[] +++ lst2 = lst2
(h:t) +++ lst2 = h:(t +++ lst2)

— zip [a1,a2,…,an] [b1,b2,…,bn] = [(a1,b1),(a2,b2),…,(an,bn)]
myzip (a:r) (b:s) = (a,b): myzip r s
myzip _ _ = []

— myzip [1..] [‘a’..’z’]
— myzip [0..127] [‘\0’..]

— mymap f [a1,a2,…,an] = [f a1,f a2,…,f an] — apply f to every argument
mymap _ [] = []
mymap f (h:t) = f h : mymap f t

— mymap (*5) [1..10]

— myflip reverves the first two arguments of a function
myflip f a b = f b a

— dotproduct lst1 lst2 is dot product of lst1 and lst2
dotproduct1 lst1 lst2 = sum (mymap (\ (x,y) -> x*y) (myzip lst1 lst2))

dotproduct2 lst1 lst2 = sum [x*y | (x,y) <- myzip lst1 lst2] -- dotproduct1 [20..30] [70..80] myuncurry f (x,y) = f x y dotproduct lst1 lst2 = sum (mymap (myuncurry (*)) (myzip lst1 lst2))