If the proposition p is true, does nothing, else fails (using failure).
8.4. API リファレンス(API Reference)
ここで説明する一般的な関数に加えて、各コレクション型の名前空間の API の一部として慣習的に定義されている関数がいくつかあります:
-
mapMはモナド関数をマップします。 -
forMはモナド関数をマップし、結果を捨てます。 -
filterMはモナド述語を使ってフィルタリングを行い、それを満たす値を返します。
モナドのコレクションに対する操作
Array.filterM を使用すると、副作用に依存したフィルタを書くことができます。
def values := #[1, 2, 3, 5, 8]
def main : IO Unit := do
let filtered ← values.filterM fun v => do
repeat
IO.println s!"Keep {v}? [y/n]"
let answer := (← (← IO.getStdin).getLine).trim
if answer == "y" then return true
if answer == "n" then return false
return false
IO.println "These values were kept:"
for v in filtered do
IO.println s!" * {v}"
stdinynoopsynystdoutKeep 1? [y/n]Keep 2? [y/n]Keep 3? [y/n]Keep 3? [y/n]Keep 5? [y/n]Keep 8? [y/n]These values were kept: * 1 * 3 * 88.4.1. 結果の破棄(Discarding Results)
discard 関数は副作用のためだけに値を返すアクションを使うときに便利です。
8.4.2. フローの制御(Control Flow)
def
guard.{v} {f : Type → Type v} [Alternative f]
(p : Prop) [Decidable p] : f Unit
def
optional.{u, v} {f : Type u → Type v}
[Alternative f] {α : Type u} (x : f α)
: f (Option α)
8.4.3. 真偽値演算子の持ち上げ(Lifting Boolean Operations)
def
andM.{u, v} {m : Type u → Type v} {β : Type u}
[Monad m] [ToBool β] (x y : m β) : m β
def
orM.{u, v} {m : Type u → Type v} {β : Type u}
[Monad m] [ToBool β] (x y : m β) : m β
def
notM.{v} {m : Type → Type v} [Applicative m]
(x : m Bool) : m Bool
8.4.4. Kleisli 合成(Kleisli Composition)
Kleisli 合成 (Kleisli composition)はモナド関数の合成で、普通の関数の Function.comp に似ています。
def
Bind.kleisliRight.{u, u_1, u_2} {α : Type u}
{m : Type u_1 → Type u_2} {β γ : Type u_1}
[Bind m] (f₁ : α → m β) (f₂ : β → m γ)
(a : α) : m γLeft-to-right composition of Kleisli arrows.
def
Bind.kleisliLeft.{u, u_1, u_2} {α : Type u}
{m : Type u_1 → Type u_2} {β γ : Type u_1}
[Bind m] (f₂ : β → m γ) (f₁ : α → m β)
(a : α) : m γRight-to-left composition of Kleisli arrows.
8.4.5. 並べ替え操作(Re-Ordered Operations)
関数の第2引数に関数を部分適用すると便利な場合があります。これらの関数は引数の順序を逆にすることでこれを簡単に行うことができます。
def
Functor.mapRev.{u, v} {f : Type u → Type v}
[Functor f] {α β : Type u}
: f α → (α → β) → f β