計算機科学のブログ

HaskellのI/O テキストとUnicodeの操作 Text型 基本的なテキストユーティリティ T.splitOnとT.intercalateによるT.linesとT.unlinesの実装

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT4(HaskellのI/O)、LESSON 23(テキストとUnicodeの操作)、23.1(Text型)、基本的なテキストユーティリティ、クイックチェック 23-3の解答を求めてみる。

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

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 where

import qualified Data.Text as T
import Lib (myTLines, myTUnlines)

t :: T.Text
t = "line1\nline2\nline3"

main :: IO ()
main = do
  print t
  print $ myTLines t
  print $ myTUnlines $ myTLines t

lesson/src/Lib.hs

module Lib
  ( myTLines,
    myTUnlines,
  )
where

import qualified Data.Text as T

myTLines :: T.Text -> [T.Text]
myTLines = T.splitOn "\n"

myTUnlines :: [T.Text] -> T.Text
myTUnlines = T.intercalate "\n"

入出力結果(Terminal, Zsh)

% stack exec lesson-exe
"line1\nline2\nline3"
["line1","line2","line3"]
"line1\nline2\nline3"
%