This question was also asked on F# Slack, but since that's not visible to the wider community, and since I don't have a solution yet, I figured it made sense to ask it here.
Basically, String.Create
works with Span
to create a new string and takes a delegate to fill the span. This is generally faster than changing a string the normal way: create a char
array, call AsSpan
, and calling the proper String
constructor with the result.
This works fine:
let create value =
String.Create(12, value, fun buf v->
for i = 0 to buf.Length do
buf.[i] <- v)
But the minute I try to use a function that's curried, or try to use a delegate, I get a type error. According to F#, the delegate is of type SpanAction<'T, 'TArg>
, where 'T
translates to Span<'T>
in the callback, and 'TArg
is any argument you can use to prevent a closure.
I've tried several variants, but all come down to this basic idea:
type SpanDelegate<'T, 'TArg> = delegate of Span<'T> * 'TArg -> unit
let callback =
new SpanDelegate<char, char>(fun buf v ->
for i = 0 to buf.Length do buf.[i] <- v)
let create (value: char) =
String.Create(12, value, callback) // type error on callback
Whether or not I use it with the original lambda, I can't seem to get it to work. Ideas are welcome:).
The reason why your code does not work is that you are creating a custom delegate SpanDelegate
, but the code expects a pre-defined delegate SpanAction
.
I'm not exactly sure I understand your issue correct (and so I may be missing something), but if you create the pre-defined SpanAction
delegate, then everything seems to be working fine:
open System
open System.Buffers
let callback =
SpanAction<char, char>(fun buf v ->
for i = 0 to buf.Length do buf.[i] <- v)
let create (value: char) =
String.Create(12, value, callback)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.