Created
September 27, 2019 23:05
-
-
Save Ou42/0fcbbdcff293a2f7a26d2699aa8f65bb to your computer and use it in GitHub Desktop.
FutureLearn: Functional Programming in Haskell - Speller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{- | |
2019-09-27 | |
Write a Spelling Book Generator | |
. Are you familiar with children’s alphabetical spelling books? | |
They say things like: a is for apple, b is for baby, and c is for cat | |
. Now that you know about Haskell list functions, you can develop a function | |
to generate the text for a spelling book, given a list of words. | |
. Your task is to develop the Haskell speller function. You are allowed to | |
define small helper functions, perhaps to generate a single letter’s phrase | |
from a word: f "zoo" -- > "z is for zoo". You are also allowed to use the | |
standard Haskell list functions like map and foldr if appropriate. | |
-} | |
-- word | |
-- helper function to take a string & return a string | |
-- in the format like, "apple" -> "a is for apple" | |
word :: [Char] -> [Char] | |
word [] = [] | |
word xs = (head xs) : " is for " ++ xs | |
-- appendCommaAndAnd | |
-- helper function that takes a word & a list of words & returns a word | |
-- if it's the last word in the list, prepend "and " | |
-- otherwise, append ", " | |
appendCommaAndAnd :: [Char] -> [[Char]] -> [Char] | |
appendCommaAndAnd w [] = "and " ++ w | |
appendCommaAndAnd w _ = w ++ ", " | |
-- acaa | |
-- assign shorter function name to appendCommaAndAnd | |
acaa = appendCommaAndAnd | |
-- speller | |
-- function that takes a list of words and returns a String | |
-- take a list of words and convert them to the "a is for apple" format | |
-- separate words by ", " | |
-- if > 1 words, include "and " before last word | |
speller :: [[Char]] -> [Char] | |
speller [] = [] | |
speller [w] = word w | |
speller ws = concat $ foldr (\w acc -> (acaa (word w) acc) : acc) [] ws | |
-- explanation: | |
-- . foldr returns a list of Strings | |
-- . concat take a list of Strings and returns a concatenated String | |
-- . :load Speller.hs | |
-- . then run it via, speller ["almost", "beautiful", "code"] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment