計算機科学のブログ

コードの整理とプロジェクトのビルド Monad型クラス 演習:素数ライブラリの作成 素数ライブラリの拡張

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT6(コードの整理とプロジェクトのビルド)、LESSON37(演習:素数ライブラリの作成)、37.6(まとめ)、素数ライブラリの拡張を実装してみる。

package.yaml

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

dependencies:
- base >= 4.7 && < 5

library:
  source-dirs: src

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

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

コード

app/Main.hs

module Main where

import Primes

main :: IO ()
main = do
    putStrLn "Enter a number to check if it's prime:"
    line <- getLine
    let n = read line :: Int
    putStrLn $ if isPrime n == Just True
               then "It is prime!"
               else "It isn't prime."
    putStrLn "Enter a number to Factors:"
    line <- getLine
    let m = read line :: Int
    let factors = primeFactors m
    putStrLn $ if factors == Nothing
               then "Sorry, this number is not a valid candidate for primality testing"
               else show factors

入出力結果(Terminal, Zsh)

% stack exec primes-exe
Enter a number to check if it's prime:
5
It is prime!
Enter a number to Factors:
100000000000
Sorry, this number is not a valid candidate for primality testing
% stack exec primes-exe
Enter a number to check if it's prime:
5
It is prime!
Enter a number to Factors:
5
Just [5]
% stack exec primes-exe
Enter a number to check if it's prime:
10
It isn't prime.
Enter a number to Factors:
10
Just [2,5]
% stack exec primes-exe
Enter a number to check if it's prime:
-10
It isn't prime.
Enter a number to Factors:
0
Sorry, this number is not a valid candidate for primality testing
% stack exec primes-exe
Enter a number to check if it's prime:
100
It isn't prime.
Enter a number to Factors:
100
Just [2,2,5,5]
%