○ Exercise 5.8
doubleAll :: [Int] -> [Int]
doubleAll xs = [2*x | x <- xs]
Main> doubleAll [1,2,3]
[2,4,6]
Main> doubleAll []
[]
○ Exercise 5.9
import Char
toupper :: Char -> Char
toupper c
| ('a' <= c) && (c <= 'z') = chr ( ord c + ord 'A' - ord 'a')
| otherwise = c
isLetters :: Char -> Bool
isLetters c
| ('a' <= c) && (c <= 'z') = True
| ('A' <= c) && (c <= 'Z') = True
| otherwise = False
capitalize :: String -> String
capitalize s = [toupper c | c <- s]
capitalizeLetters :: String -> String
capitalizeLetters s = [toupper c | c <- s, isLetters c]
Main> capitalize "aabbCdE"
"AABBCDE"
Main> capitalize "aabbC--dE"
"AABBC--DE"
Main> capitalizeLetters "aabbC--dE"
"AABBCDE"
Main>
○ Exercise 5.10
divisors :: Int -> [Int]
divisors n = [x | x <- [1 .. n], n `mod` x == 0]
isPrime :: Int -> Bool
isPrime n = (length (divisors n)) == 2
Main> divisors 12
[1,2,3,4,6,12]
Main> divisors 7
[1,7]
Main> isPrime 12
False
Main> isPrime 7
True
Main>
○ Exercise 5.11
matches :: Int -> [Int] -> [Int]
matches x ys = [y | y<- ys, y == x]
elem :: Int -> [Int] -> Bool
elem x ys = (length (matches x ys)) /= 0
Main> matches 1 [1,2,1,3,1,4]
[1,1,1]
Main> elem 1 [1,2,1,3,1,4]
True
Main> matches 1 [2,3,4]
[]
Main> elem 1 [2,3,4]
False
Main>
1 comment:
Hey Would you post the solution for exercise 5.22,5.23 and 5.26 and from Chapter 7 as well.
Post a Comment