2017年2月5日日曜日

開発環境

関数プログラミング入門(Richard Bird (著)、山下伸夫 (翻訳)、オーム社)の第1章(基本概念)、1.5(定義)、練習問題1.5.1、1.5.2を取り組んでみる。

練習問題1.5.1、1.5.2

コード(Emacs)

-- 1.5.1
fib :: Integer -> Integer
fib n
  | n < 0 = error "negative argument to fibonacci"
  | n == 0 || n == 1 = n
  | otherwise = fib (n - 1) + fib (n - 2)

-- 1.5.2  
abs :: Integer -> Integer
abs n = if n < 0 then -n else n

入出力結果(Terminal, ghci)

$ ghci sample5.hs
GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Main             ( sample5.hs, interpreted )
Ok, modules loaded: Main.
*Main> fib -1

<interactive>:1:1: error:
    • No instance for (Num (Integer -> Integer))
        arising from a use of ‘-’
        (maybe you haven't applied a function to enough arguments?)
    • In the expression: fib - 1
      In an equation for ‘it’: it = fib - 1
*Main> fib (-1)
*** Exception: negative argument to fibonacci
CallStack (from HasCallStack):
  error, called at sample5.hs:4:13 in main:Main
*Main> fib 0
0
*Main> fib 1
1
*Main> fib 2
1
*Main> fib 10
55
*Main> fib 20
6765
*Main> abs (-10)

<interactive>:8:1: error:
    Ambiguous occurrence ‘abs’
    It could refer to either ‘Prelude.abs’,
                             imported from ‘Prelude’ at sample5.hs:1:1
                             (and originally defined in ‘GHC.Num’)
                          or ‘Main.abs’, defined at sample5.hs:9:1
*Main> Main.abs (-10)
10
*Main> Main.abs 0
0
*Main> Main.abs 1
1
*Main> Main.abs 10
10
*Main> :q
Leaving GHCi.
$

0 コメント:

コメントを投稿

Comments on Google+: