代写代考 — Sum all the numbers from 0 to n

— Sum all the numbers from 0 to n
sumTo :: Int -> Int
sumTo 0 = 0
| n > 0 = n + sumTo(n-1)

Copyright By PowCoder代写 加微信 powcoder

| otherwise = error “Not a natural number.”

— If we read this as an inductive definition, then
— Nat is the (smallest) set of things you can apply by
— using the formation rules of the datatype finitely many times
— 2. Given that we already have a number n,
— we can make another number S(n)
— (technically, it’s a coinductive definition, but never mind)
data Nat = Z | S Nat
deriving Show
— 0 is represented by Z
— 1 is represented by S Z
— 2 is represented by S(S Z)

add :: Nat -> Nat -> Nat
add Z n = n
add (S n) m = S(add n m)

— a is a type variable: placeholder for an arbitrary type
mylength :: [a] -> Nat
mylength [] = Z
mylength (x:xs) = S(mylength xs)

mytake :: Nat -> [a] -> [a]
mytake Z xs = []
mytake n [] = []
mytake (S n) (x:xs) = x:mytake n xs

mydrop :: Nat -> [a] -> [a]
mydrop Z xs = xs
mydrop n [] = []
mydrop (S n) (x:xs) = mydrop n xs

data Tree a = Leaf
| Branch a (Tree a) (Tree a)
deriving Show

— Node “5” (Cons (Node “5” Empty) (Cons (Node “5” Empty) Empty))

/ | \ which has three nested Conses for its children (one each for 1 2 3)

A Node is a rose tree node
A Cons is a collection of tree nodes (containing at least one rose aka Node)

leaves :: Tree a -> Int
leaves Leaf = 1
— _ pattern: I don’t care what the node is, so we don’t give it name
leaves (Branch _ l r) = leaves l + leaves r

height :: Tree a -> Int
height Leaf = 0
height (Branch _ l r) = 1 + max (height l) (height r)

— A rose tree is a tree with an unlimited amount of branches per node
— unlike the trees above which have two branches per node
data Forest a = Empty | Cons (Rose a) (Forest a)
deriving Show
data Rose a = Node a (Forest a)
deriving Show

rheight :: Rose a -> Int
rheight (Node _ f) = 1 + rheight’ f
rheight’ :: Forest a -> Int
rheight’ Empty = 0
rheight’ (Cons r f) = max (rheight r) (rheight’ f)

rsize :: Rose a -> Int
rsize (Node _ f) = 1 + rsize’ f
rsize’ :: Forest a -> Int
rsize’ Empty = 0
rsize’ (Cons r f) = rsize r + rsize’ f

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com