計算機科学のブログ

コードの整理とプロジェクトのビルド Haskellコードをモジュールにまとめる String型とText型、Data.Textモジュール

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT6(コードの整理とプロジェクトのビルド)、LESSON 34(Haskellコードをモジュールにまとめる)、34.4(練習問題)Q34-1の解答を求めてみる。

lesson/package.yaml

name:                lesson
version:             0.1.0.0
github:              "githubuser/lesson"
license:             BSD3
author:              "Author name here"
maintainer:          "example@example.com"
copyright:           "2022 Author name here"

extra-source-files:
- README.md
- CHANGELOG.md

# Metadata used when publishing your package
# synopsis:            Short description of your package
# category:            Web

# To avoid duplicated efforts in documentation and dealing with the
# complications of embedding Haddock markup inside cabal files, it is
# common to point users to the README.md file.
description:         Please see the README on GitHub at <https://github.com/githubuser/lesson#readme>

dependencies:
- base >= 4.7 && < 5
- text

ghc-options:
- -Wall
- -Wcompat
- -Widentities
- -Wincomplete-record-updates
- -Wincomplete-uni-patterns
- -Wmissing-export-lists
- -Wmissing-home-modules
- -Wpartial-fields
- -Wredundant-constraints

library:
  source-dirs: src

executables:
  lesson-exe:
    main:                Main.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - lesson

tests:
  lesson-test:
    main:                Spec.hs
    source-dirs:         test
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - lesson
default-extensions:
  - OverloadedStrings

コード

lesson/app/Main.hs

module Main (main) where

import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Palindrome

text :: T.Text
text = "A man, a plan, a canal: Panama!"

main :: IO ()
main = do
  TIO.putStrLn text
  print $ isPalindrome text
  TIO.putStrLn "Haskell"
  print $ isPalindrome "haskell"

lesson/src/Palindrome.hs

module Palindrome
  ( isPalindrome,
  )
where

import Data.Char
  ( isPunctuation,
    isSpace,
    toLower,
  )
import qualified Data.Text as T

stripWhiteSpace :: T.Text -> T.Text
stripWhiteSpace = T.filter (not . isSpace)

stripPunctuation :: T.Text -> T.Text
stripPunctuation = T.filter (not . isPunctuation)

toLowerCase :: T.Text -> T.Text
toLowerCase = T.map toLower

preprocess :: T.Text -> T.Text
preprocess = stripWhiteSpace . stripPunctuation . toLowerCase

isPalindrome :: T.Text -> Bool
isPalindrome text =
  let cleanText = preprocess text
   in cleanText == T.reverse cleanText

入出力結果(Terminal, Zsh)

% stack exec lesson-exe
A man, a plan, a canal: Panama!
True
Haskell
False
%