so what I mean by loop unroll is like
Write "Hello" |> Repeat开发者_运维知识库 5
->>>
Write "Hello"
Write "Hello"
Write "Hello"
Write "Hello"
Write "Hello"
as far as I know that is some optimization and I just interesting if that possible on .NET
By the way - Simply why I must use for i in [0..4] do ... if I don't really not this [0..4] and I don't really need this i ...
The F# language doesn't directly support this form of meta-programming. What you're asking for is usually called multi-stage programming and there are ML-based languages that support it (search for example for MetaML). In these languages, you can manipulate with compiled code and (e.g.) unroll loops.
A limited form of this can be done in F# using quotations. It isn't very practical though, because F# quotation compiler generates slower code (so it definitely doesn't work as an optimization).
However, just for a curiosity, here is how to achieve this using quotations and quotation compiler from F# PowerPack:
#r @"FSharp.PowerPack.Linq.dll"
open Microsoft.FSharp.Linq.QuotationEvaluation
// Generate quotation that contains 5 prints followed by expression that returns unit
let unrolled = [ 1 .. 5 ] |> List.fold (fun expr _ ->
<@ printfn "Hello"; %expr @>) <@ () @>
// Compile the function once & run it two times
let f = unrolled.Compile()
f()
f()
... as I mentioned, this isn't useful as an optimization, because the Compile
method produces slow code, but it is useful in some other scenarios.
You may write for _ in 0..4
to indicate that you don't need the value of the loop variable.
Doing something like loop unrolling on the F# language level would require support for macros. In languages like Lisp or Clojure you could do that. But usually it is better to let the compiler or the runtime worry about that.
On the IL level, you could implement things like loop unrolling using classes of the System.Reflection.Emit
namespace (or using a library like Cecil for that).
You can't do without 'for', but you can abstract it in your own function
let Write msg =
fun () -> printfn msg
let Repeat n f =
for _ in 1..n do
f()
Write "Hello" |> Repeat 5
精彩评论