1
1

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 第4章

1
Last updated at Posted at 2015-03-31

関数定義

・関数定義の最も簡単な方法は既存の関数を組合せること

例.数字文字であるか検査する

isDegit c = c => '0' && c =< '9'

実行結果
*Main> isDegit 'a'
False
*Main> isDegit '3'
True

条件式

・文法はif 条件 then Trueの時の処理 else Falseの時の処理
・Haskellは必ずelse部を持つ必要がある

例.絶対値を取得する
⇒引数が負値の場合、値を括弧で括らなければエラーとなる(引っかかった)

abs_org n = if n >= 0 then n else -n

実行結果
*Main> abs_org 1
1
*Main> abs_org (-11)
11

ガード付きの等式

・関数は条件式を使う代わりに、ガード付きの等式を使って定義することもできる
・ガードと呼ばれる論理式の中から、最初にTrueとなるガードの結果が採用される
・otherwiseは必ずTrueとなるため、「他のすべての場合」を処理する場合に便利
・条件式に比べ、条件が多くなった場合に読みやすい

例.絶対値を取得する(ガードを使った場合)

Haskell
abs_guard n | n >= 0 = n 
            | otherwise = -n

実行結果
*Main> abs_guard 4
4
*Main> abs_guard (-4)
4

パターンマッチ

・列挙された同じ型のパターンの中から、最初に合致した結果が利用される。
・すべての値に合致するワイルドカードはアンダースコア「_」
・1つの等式において、2つ以上の引数が同じ名前を持つ事は許されない。

例.論理積(&&)を実装

Haskell
and_org True True = True
and_org _ _ = False

実行結果
*Main> True `and_org` False
False
*Main> True `and_org` True
True
*Main> False `and_org` False
False
*Main> False `and_org` True
False

次のコードはNG

Haskell
-- bの引数名が重複している
b `and_org2` b = b
_ `and_org2` _ = False

2つの引数が同等か確かめる必要があるということであれば、ガードを用いる

Haskell
b `and_org2` c | b == c = b
               | otherwise = False

タプル・パターン、リスト・パターン

・タプルやリストもパターンマッチに用いることができる。
・Haskellのリストは合成されたデータ。リストは空のリスト[]に対し、演算子:を使って
 要素を1つずつ増やしていくことで生成される
 ⇒リストは先頭と先頭以外に分離できる
・演算子:は「作成する」(construct)を意味する「cons演算子」と呼ばれる
・リストは次のように分解できる

[1,2,3]

1:[2,3]

1:(2:[3])

1:(2:(3:[]))

今日はここまで

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?