Functional programming 如何在kind';中重复一元指令;什么是单子?
我知道我可以在monads中以语言顺序运行monadic指令,如下所示:Functional programming 如何在kind';中重复一元指令;什么是单子?,functional-programming,monads,kind,Functional Programming,Monads,Kind,我知道我可以在monads中以语言顺序运行monadic指令,如下所示: Test: _ IO { IO.print(Nat.show(2)) IO.print(Nat.show(3)) IO.print(Nat.show(4)) } 但是有可能像下面这样重复运行一元指令吗 Test: _ a = [2,1,3,4,5] IO { for num in a: IO.print(Nat.show(num)) } 如果可能,我如何才能正确
Test: _
IO {
IO.print(Nat.show(2))
IO.print(Nat.show(3))
IO.print(Nat.show(4))
}
但是有可能像下面这样重复运行一元指令吗
Test: _
a = [2,1,3,4,5]
IO {
for num in a:
IO.print(Nat.show(num))
}
如果可能,我如何才能正确地执行此操作?单子通常仅由两个运算符表示:
return :: a -> m(a) // that encapulapse the value inside a effectful monad
>>= :: m a -> (a -> m b) -> m b
// the monadic laws are omitted
请注意,bind操作符自然是递归的,一旦它可以组成两个monad,甚至可以丢弃其中一个的值,那么返回可以被认为是“基本情况”
你只需要产生这个序列,这是非常简单的。例如,在实物中,我们将单子表示为一对,以类型作为类型值,并封装多态类型
type Monad <M: Type -> Type> {
new(
bind: <A: Type, B: Type> M<A> -> (A -> M<B>) -> M<B>
pure: <A: Type> A -> M<A>
)
}
目前,Kind不支持typeclass,因此它会让事情变得更详细,但我认为将来可以考虑对forM循环语法的新支持。我们希望如此:)我不知道种类,但它提供递归吗?@Bergi是的,它提供递归,它是一种功能性的“校对编程”语言。感谢您提供这个非常完整的答案!在基本目录中有这个
foldM
和forM
(可能还有forM
的语法)会很好。
m >>= (\a -> ... >>= (\b -> ~ i have a and b, compose or discard? ~) >>= fixpoint)
type Monad <M: Type -> Type> {
new(
bind: <A: Type, B: Type> M<A> -> (A -> M<B>) -> M<B>
pure: <A: Type> A -> M<A>
)
}
action (x : List<String>): IO(Unit)
case x {
nil : IO.end!(Unit.new) // base case but we are not worried about values here, just the effects
cons : IO {
IO.print(x.head) // print and discard the value
action(x.tail) // fixpoint
}
}
test : IO(Unit)
IO {
let ls = ["2", "1", "3", "4", "5"]
action(ls)
}
Monadic.forM(A : Type -> Type, B : Type,
C : Type, m : Monad<A>, b : A(C), f : B -> A(C), x : List<A(B)>): A(C)
case x {
nil : b
cons :
open m
let k = App.Kaelin.App.mapM!!!(m, b, f, x.tail)
let ac = m.bind!!(x.head, f)
m.bind!!(ac, (c) k) // the >> operator
}
action2 (ls : List<String>): IO(Unit)
let ls = [IO.end!(2), IO.end!(1), IO.end!(3), IO.end!(4), IO.end!(5)]
Monadic.forM!!!(IO.monad, IO.end!(Unit.new), (b) IO.print(Nat.show(b)), ls)
Monadic.foldM(A : Type -> Type, B : Type,
C : Type, m : Monad<A>, b : A(C), f : B -> C -> A(C), x : List<A(B)>): A(C)
case x {
nil : b
cons :
open m
let k = Monadic.foldM!!!(m, b, f, x.tail)
m.bind!!(x.head, (b) m.bind!!(k, (c) f(b, c)))
}
Monad.action3 : IO(Nat)
let ls = [IO.get_line, IO.get_line, IO.get_line]
Monadic.foldM!!!(IO.monad, IO.end!(0),
(b, c) IO {
IO.end!(Nat.add(Nat.read(b), c))
},
ls)
test : IO(Unit)
IO {
get total = action3
IO.print(Nat.show(total))
}