Concatenating strings in F# number of times

十年热恋 提交于 2019-12-11 06:56:31

问题


I'm trying to concatenate a string with a certain amount of times, but I feel like I've cheated a bit (or at least not actually understood how it's supposed to be done) by using a higher-order function:

let repeat s n = 
String.replicate n s |> printfn "%s"

repeat "a" 10

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


回答1:


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

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

repeat "a" 10

or in a more "classic" style with an if-expression:

let rec repeat s n =
    if n <= 0 then
        ""
    else
        s + (repeat s (n-1))

repeat "a" 10



回答2:


And here's one way using list comprehension and fold, which is the go to function for recursion:

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

Tail Recursive version

let repeat2 s n =
    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 amounts of gen2 GC and a few min. of runtime.



来源:https://stackoverflow.com/questions/40299925/concatenating-strings-in-f-number-of-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!