Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating strings in F# number of times

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.

like image 443
Left4Cookies Avatar asked Sep 01 '25 16:09

Left4Cookies


1 Answers

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
like image 93
CodeMonkey Avatar answered Sep 04 '25 06:09

CodeMonkey