## 2017年2月5日日曜日

### Haskell - 基本概念 - 関数(ガード不等式、再帰定義)

コード(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
```

```\$ ghci sample5.hs
GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Main             ( sample5.hs, interpreted )
*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.
\$
```