String concatenation in F # number of times

I am trying to concatenate a string with a certain number of times, but it seems to me that I have changed a bit (or at least not understood how this should be done) using a higher order function:

let repeat sn = String.replicate ns |> printfn "%s" repeat "a" 10 

Obviously gives me "aaaaaaaaaa", but how could I do this without a higher order function? I feel this is a very simple problem, but I can’t wrap my head around me, the F # syntax or way of thinking is still troublesome for me.

+1
source share
2 answers

If you just need a recursive solution, how about this?

 let rec repeat sn = match n with | _ when n <= 0 -> "" | _ -> s + (repeat s (n-1)) repeat "a" 10 

or in a more "classic" style with an if statement:

 let rec repeat sn = if n <= 0 then "" else s + (repeat s (n-1)) repeat "a" 10 
+3
source

And here is one way that uses list comprehension and bending, which is a function for recursion:

[for i in 1..10 -> "a"] |> List.fold (+) ""

Fractal tail version

 let repeat2 sn = let rec loop acc n = match n with | _ when n > 0 -> loop (acc + s) (n - 1) | _ -> acc loop "" n repeat "oijdfsaoijdoyasjd" 100000 // Process is terminated due to StackOverflowException. [for i in 1..100000 -> "oijdfsaoijdoyasjd"] |> List.fold (+) "" // no stack overflow repeat2 "oijdfsaoijdoyasjd" 100000 // no stack overflow 

But prepared for massive quantities of GC2 GC and a few minutes. runtime.

+2
source

Source: https://habr.com/ru/post/1012127/


All Articles