Haskell/Solutions/Higher-order functions and Currying
From Wikibooks, the open-content textbooks collection
← Back to Higher-order functions and Currying
[edit] quickSort, Take Two
| Exercises |
|---|
Write insensitive, such that quickSort insensitive dictionary gives ["a", "for", "have", "I", "Linux", "thing"] |
import Data.Char (toUpper) insensitive string1 string2 = compare (map toUpper string1) (map toUpper string2)
Instead of comparing the two strings directly, we compare the all uppercase version. The order of the original two strings is then based on the order of the uppercase versions.
[edit] Higher-Order Functions and Types
| Exercises |
|---|
The following exercise combines what you have learned about higher order functions, recursion and IO. We are going to recreate what programmers from more popular languages call a "for loop". Implement a function
for :: a -> (a->Bool) -> (a->a) -> (a-> IO ()) -> IO () for i p f job = -- ???An example of how this function would be used might be for 1 (<10) (+1) (\x -> print x)which prints the numbers 1 to 10 on the screen. Starting from an initial value
Some more challenging exercises you could try
|
|
This exercise was inspired from a blog post by osfameron. |
Part 1:
2. A for loop in Haskell:
for :: a -> (a->Bool) -> (a->a) -> (a->IO()) -> IO()
for i p f job =
if p i
then do
job i
for (f i) p f job
else return ()
*Main> for 0 (<3) (+1) (print)
0
1
2
Part 2:
1. The blog shows a more advanced method but:
printNums i j = [i..j] *Main> printNums 1 10 [1,2,3,4,5,6,7,8,9,10]
2.
sequenceIO :: [IO a] -> IO [a]
sequenceIO [] = return []
sequenceIO (a:as) = do {v <-a ; vs <- (sequenceIO as) ; return (v : vs)}
In this function, the `vs <- (sequenceIO as)' section recursively calls sequenceIO to generate the rest of the passed list, using `<-' extract the values of each returned IO object, and then finally returns the IO object with `v' Consed onto the generated list, `vs'.
3.
mapIO :: (a -> IO b) -> [a] -> IO [b]
mapIO f [] = return []
mapIO f (x:xs) = do {y <- (f x) ; ys <- (mapIO f xs) ; return (y : ys)}