Skip to content

Commit

Permalink
(WIP) Useful example of undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
igrep committed Oct 31, 2021
1 parent e81a2e5 commit 6d24b6f
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions assets/12.md
Expand Up @@ -127,6 +127,31 @@ bmiFromStrings :: String -> String -> Double
bmiFromStrings = undefined
```

この`bmiFromStrings`と前述の`main`関数を同じファイルに書いてGHCiで読み込むとあら不思議、何のエラーも出ません!そのまま`main`関数を実行するとどうなるのでしょうか?

```haskell
ghci> main
Height Weight:
120 90 -- とりあえず身長と体重両方を入力してみる
*** Exception: Prelude.undefined
CallStack (from HasCallStack):
error, called at libraries\base\GHC\Err.hs:79:14 in base:GHC.Err
undefined, called at <interactive>:22:18 in interactive:Ghci1
```

この課題の最初の方で`undefined`を入力したときと同様に`*** Exception: Prelude.undefined`と表示されました。これはまさしく`bmiFromStrings`関数を定義するときに書いた`undefined``String -> String -> Double`型の値、すなわち「文字列を二つ受け取って数値を返す関数」として評価しようとして発生した例外によるものです。

このように、`undefined`

hoge

例外が発生したときに表示するメッセージをもっと分かりやすくしたいときは?そう、`error`関数を使いましょう。関数の名前も書いておくとより親切なので、私はそういうスニペットをエディターに設定しています:

```haskell
bmiFromStrings :: String -> String -> Double
bmiFromStrings = error "bmiFromStrings is not defined yet!"
```

hoge

#### `read`関数が文字列からの変換に失敗したとき
Expand Down

0 comments on commit 6d24b6f

Please sign in to comment.