代写 Exercise 2 – Guard Equations & Local Functions

Exercise 2 – Guard Equations & Local Functions
1 Example
“countup” in Exam 1.
2 Exercises
Hao Tian March 2019
Try to write following exercises using Local Functions.
1. Please filter values from a list that greater than its prior value. For example, greaterthanlast [1,2,1,3,4,5,1,3] = [2,3,4,5,3]
Answer:
greaterthanlast :: [Int]− > [Int]
greaterthanlast :: [Int]− > [Int] greaterthanlast [ ] = [ ] greaterthanlast [x] = [ ] greaterthanlast (x : y : xs)
|y > x = y : greaterthanlast (y : xs) |otherwise = greaterthanlast (y : xs)
2. Please determine whether a string is palindrome without extra space. For example, ispalindrome “abcba” = True.
One can use ispalindrome w = w == reverse w but it is less efficient comparing to “two pointers” solution. That is, compare first and last char, then second and second last and so on.
Answer:
ispalindrome :: String− > Bool
ispalindrome [ ] = T rue
ispalindrome [x] = T rue
ispalindrome w = (head w == last w) && ispalindrome middle
|where middle = (init . tail) w
1