Real World Haskell - 第4章 Exercises Part1
Real World Haskell で Haskell を継続的に勉強中。
Chapter 4. Functional programming
Chapter 4. Functional programming
回答は順次追記していく。
Excercises (Section "Special string-handling functions" の後にあるもの)
1.Write your own “safe” definitions of the standard partial list functions, but make sure that yours never fail. As a hint, you might want to consider using the following types.
-- file: ch04/ch04.exercises.hs safeHead :: [a] -> Maybe a safeTail :: [a] -> Maybe [a] safeLast :: [a] -> Maybe a safeInit :: [a] -> Maybe [a]2.Write a function splitWith that acts similarly to words, but takes a predicate and a list of any type, and splits its input list on every element for which the predicate returns False.
-- file: ch04/ch04.exercises.hs splitWith :: (a -> Bool) -> [a] -> [[a]]3.Using the command framework from the section called “A simple command line framework”, write a program that prints the first word of each line of its input.
4.Write a program that transposes the text in a file. For instance, it should convert "hello\nworld\n" to "hw\neo\nlr\nll\nod\n".
1
safeHead x | null x = Nothing | otherwise = Just (head x) safeTail x | null x = Nothing | otherwise = Just (tail x) safeLast x | null x = Nothing | otherwise = Just (last x) safeInit x | null x = Nothing | otherwise = Just (init x)
これもあり。
safeListFunc func [] = Nothing safeListFunc func xs = Just (func xs) safeHead = safeListFunc head safeTail = safeListFunc tail safeLast = safeListFunc last safeInit = safeListFunc init