計算機科学のブログ

Haskell - 実践Haskell - HaskellのエラーとEither型 - head関数、部分関数、エラー

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT 7(実践Haskell)、LESSON 38(HaskellのエラーとEither型)、36.5(head関数、部分関数、エラー)、 Q36-1の解答を求めてみる。

軽量マークアップ言語

headaches/package.yaml

name:                headaches
version:             0.1.0.0
github:              "githubuser/headaches"
license:             BSD-3-Clause
author:              "Author name here"
maintainer:          "example@example.com"
copyright:           "2025 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/headaches#readme>

dependencies:
- base >= 4.7 && < 5

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:
  headaches-exe:
    main:                Main.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - headaches

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

コード

headaches/app/Main.hs

module Main (main) where

import Lib

main :: IO ()
main = do
    mapM_ print ([myTakePM 0 [1 .. 5],
        myTakePM 1 [],
        myTakePM 5 [1 ..]] :: [[Int]])

コード

headaches/src/Lib.hs

module Lib
    ( myTakePM
    ) where

myTakePM :: Int -> [a] -> [a]
myTakePM 0 _ = []
myTakePM _ [] = []
myTakePM n (x:xs) = x:myTakePM (n - 1) xs

入出力結果(Terminal, Zsh)

% stack exec headaches-exe
[]
[]
[1,2,3,4,5]
%