計算機科学のブログ

実践Haskell HTTPリクエストの作成 プロジェクトを準備する 最初のコード LANGUAGEプラグマ、OverloadedStrings

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT7(実践Haskell)、LESSON39(HaskellでのHTTPリクエストの作成)、39.1(プロジェクトを準備する)、クイックチェック 39-1の解答を求めてみる。

LANGUAGEプラグマを使用してOverloadedStringsを追加すればいい。

package.yaml

name:                http-lesson
version:             0.1.0.0
github:              "githubuser/http-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/http-lesson#readme>

dependencies:
- base >= 4.7 && < 5

library:
  source-dirs: src

executables:
  http-lesson-exe:
    main:                Main.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - http-lesson
    - bytestring
    - http-conduit
    # default-extensions: OverloadedStrings

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

コード

Main.hs

{-# LANGUAGE OverloadedStrings #-}

module Main where

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as LC
import Network.HTTP.Simple

main :: IO ()
main = do
  print "hi"

入出力結果(Terminal, Zsh)

% stack build
http-lesson-0.1.0.0: unregistering (local file changes: app/Main.hs)
http-lesson> build (lib + exe)
Preprocessing library for http-lesson-0.1.0.0..
Building library for http-lesson-0.1.0.0..
Preprocessing executable 'http-lesson-exe' for http-lesson-0.1.0.0..
Building executable 'http-lesson-exe' for http-lesson-0.1.0.0..
[2 of 2] Compiling Main
[1 of 2] Compiling Main [flags changed]
Linking .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/http-lesson-exe/http-lesson-exe ...
http-lesson> copy/register
Installing library in /Users/…/http-lesson/.stack-work/install/x86_64-osx/e8aa255f05230c729a6925540310c5d25fa2ee7edb295ecd65b1d55a14d8280b/9.0.2/lib/x86_64-osx-ghc-9.0.2/http-lesson-0.1.0.0-7VoYrQcVxswJmRwg5jgroZ
Installing executable http-lesson-exe in /Users/…/http-lesson/.stack-work/install/x86_64-osx/e8aa255f05230c729a6925540310c5d25fa2ee7edb295ecd65b1d55a14d8280b/9.0.2/bin
Registering library for http-lesson-0.1.0.0..
% stack exec http-lesson-exe
"hi"
%