计算表达式

This commit is contained in:
Sanchime 2022-02-26 14:52:20 +08:00
parent 12cce6d8b4
commit ee20268ce2
2 changed files with 106 additions and 0 deletions

View File

@ -2,6 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>6.0</LangVersion>
<RootNamespace>Basic_practice_of_FSharp</RootNamespace>
</PropertyGroup>
<ItemGroup>
@ -16,5 +17,6 @@
<Compile Include="Loop.fs" />
<Compile Include="TypeCreating.fs" />
<Compile Include="PatternMatching.fs" />
<Compile Include="ComputationExpressions.fs" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,104 @@
module ComputationExpressions
//
//
// builder-expr { cexpr }
// 计算表达式类似于一种monads,monoid, monad
// ,
// F#
//
// seq { cexpr }
// yield,便IEnumerable<T>
seq {
for i = 0 to 10 do yield i * i
}
|> printfn "%A"
//
let weekdays includeWeekdays =
seq {
""
""
""
""
""
if includeWeekdays then
""
""
}
weekdays true |> printfn "%A"
// yield!
seq {
yield! seq { for i = 0 to 3 do yield i * i }
yield! seq { for i = 0 to 3 do yield i * i * i }
}
|> Seq.iter (printf "%A ")
printf "\n"
//
// query { cexpr }
query {
for i in 1..10 do
select i
contains 5 // 5,true,false
}
|> printfn "%A"
query {
for i in 1..10 do
select i
count //
}
|> printfn "%A"
query {
for i in 1..10 do
last //
}
|> printfn "%A"
query {
for i in 1..10 do
lastOrDefault // ,,
}
|> printfn "%A"
query {
for i in 1..10 do
where (i = 4) // ,使
select i
}
|> printfn "%A"
// ...
//
// async { cexpr }
//
// task { cexpr }
//
// Yield
// 使[<CustomOpertion>]
type MyComputationBuilder() =
member this.Yield(x) = x
let mycom = MyComputationBuilder()
mycom {
yield 1
}
|> printfn "%A"