計算機科学のブログ

関数型プログラミングの基礎 高階関数 調和級数の総和、遅延評価

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 9(高階関数)、9.6(練習問題)Q9-3の解答を求めてみる。

コード

lesson/app/Main.hs

module Main where

import Lib (harmonic)

main :: IO ()
main = do
  mapM_
    ( \n ->
        putStrLn $
          mconcat
            [ "Σ 1/n = ",
              show $ harmonic n,
              " (n = ",
              show n,
              ")"
            ]
    )
    [1 .. 10]

lesson/src/Lib.hs

module Lib
  ( harmonic,
  )
where

harmonic :: (Fractional a, Enum a) => Int -> a
harmonic n = sum $ take n $ map (1.0 /) [1, 2 ..]

入出力結果(Terminal, Zsh)

% stack build          
lesson-0.1.0.0: unregistering (local file changes: src/Lib.hs)
lesson> build (lib + exe)
Preprocessing library for lesson-0.1.0.0..
Building library for lesson-0.1.0.0..
[2 of 2] Compiling Lib
Preprocessing executable 'lesson-exe' for lesson-0.1.0.0..
Building executable 'lesson-exe' for lesson-0.1.0.0..
[1 of 2] Compiling Main [Lib changed]
Linking .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/lesson-exe/lesson-exe ...
lesson> copy/register
Installing library in /Users/…/lesson/.stack-work/install/x86_64-osx/494c7f11ebc566ca0dd51f0cf6ed1f4268c15f68d59cb48ce0d42f2bf991d579/9.0.2/lib/x86_64-osx-ghc-9.0.2/lesson-0.1.0.0-CIOIkpTgcfQI9akDJnwnSd
Installing executable lesson-exe in /Users/…/lesson/.stack-work/install/x86_64-osx/494c7f11ebc566ca0dd51f0cf6ed1f4268c15f68d59cb48ce0d42f2bf991d579/9.0.2/bin
Registering library for lesson-0.1.0.0..
% stack exec lesson-exe
Σ 1/n = 1.0 (n = 1)
Σ 1/n = 1.5 (n = 2)
Σ 1/n = 1.8333333333333333 (n = 3)
Σ 1/n = 2.083333333333333 (n = 4)
Σ 1/n = 2.283333333333333 (n = 5)
Σ 1/n = 2.4499999999999997 (n = 6)
Σ 1/n = 2.5928571428571425 (n = 7)
Σ 1/n = 2.7178571428571425 (n = 8)
Σ 1/n = 2.8289682539682537 (n = 9)
Σ 1/n = 2.9289682539682538 (n = 10)
%