Background
This problem comes courtesy of the great folks over at Exercism. I highly recommend jumping on their Haskell track to apply your knowledge of Haskell.
The Problem
Your task is to figure out if a sentence is a pangram.
A pangram is a sentence using every letter of the alphabet at least once. It is case insensitive, so it doesn’t matter if a letter is lower-case (e.g. k
) or upper-case (e.g. K
).
For this exercise, a sentence is a pangram if it contains each of the 26 letters in the English alphabet.
Knowledge You Need to Solve This Problem
- Basic Functions and How to Write Them
- Elem Function
- Higher-order Functions
- Maps & Filters
- Pattern Matching
The Solution
To solve this problem in Haskell, you can create a function that checks if a given sentence contains every letter of the alphabet at least once. Here’s how you could do it:
- Define the alphabet as a list of characters.
- For each letter in the alphabet, check if it exists in the sentence using
elem
. - Ensure all letters are present to confirm it’s a pangram.
Here’s the Haskell code implementing this approach:
import Data.Char (toLower, isAlpha)
isPangram :: String -> Bool
isPangram sentence =
let lowercaseSentence = map toLower sentence
alphabet = ['a'..'z']
in all (`elem` lowercaseSentence) alphabet
Explanation:
map toLower sentence
converts the sentence to lowercase, making the check case-insensitive.alphabet = ['a'..'z']
defines the list of all lowercase alphabet letters.all (
elemlowercaseSentence) alphabet
checks if each letter inalphabet
exists inlowercaseSentence
by usingelem
for each letter.
Usage Example:
main :: IO ()
main = do
print $ isPangram "The quick brown fox jumps over the lazy dog" -- Should return True
print $ isPangram "Hello World" -- Should return False
This solution will return True
if the sentence is a pangram and False
otherwise.
💡 Helpful References
Exercism - Pangram
https://exercism.org/tracks/haskell/exercises/pangram/
Leave a Reply