11
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

コピペしてすぐ確認できるHaskellの条件分岐

Last updated at Posted at 2016-05-19

はじめに

この記事は、Haskell で条件分岐を元に作成しています。
簡潔でわかりやすいリンク元様に感謝:relaxed:しつつ、こちらでは、コピペしてそのまま確認できるものを用意してみました。

case

  • 単純なcase文
foo n =
  case n of
    0 -> 0
    1 -> 1
    _ -> -1
  • ガード条件付きcase文
foo n =
  case n of
    0 -> 0
    1 -> 1
    _  | n < 0     -> -1
       | otherwise -> error "out of range!"

またパターンマッチでは、それぞれ以下のように書くこともできます。

foo 0 = 0
foo 1 = 1
foo n = -1
foo 0 = 0
foo 1 = 1
foo n
  | n < 0     = -1
  | otherwise = error "out of range!"

if

  • 単純なif文
foo n =
    if n >= 0
      then "true"
      else "false"
  • else内でさらにif文分岐
foo n =
    if n < 0
      then "negative"
      else if n > 0
        then "positive"
        else "zero"

ガード

foo n
  | n < 0     = error "fibo out of range"
  | n < 2     = 1
  | otherwise = foo (n - 1) + foo (n - 2)

ちなみに上記はフィボナッチ数列です。1

ifをcaseに変換する

foo b =
  case b of
    True  -> 1
    False -> 0

ガードを case に変換する

foo n = 
  case n of
    _  | n < 0     -> error "fibo out of range"
       | n < 2     -> 1
       | otherwise -> foo (n - 1) + foo (n - 2)
  1. 参考:http://www.geocities.jp/m_hiroi/func/haskell03.html

11
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?