Pangram Problem – Haskell [Problem Solved]

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

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:

  1. Define the alphabet as a list of characters.
  2. For each letter in the alphabet, check if it exists in the sentence using elem.
  3. 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 (elem lowercaseSentence) alphabet checks if each letter in alphabet exists in lowercaseSentence by using elem 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.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *