String Multiplication in F #

I have a question that I'm pretty unsure about.

My questions are as follows:

let myFunc (text:string) (times:int) = .... 

What I want this function to execute puts the string together as many times as specified by the times parameter.

if input = "check " 3 I want the output line = "check check check"

I tried with a loop but could not get it to work.

Is anyone

+1
source share
5 answers

Actually the function is already in String :

 let multiply text times = String.replicate times text 

To write your own function, an efficient way is to use StringBuilder :

 open System.Text let multiply (text: string) times = let sb = new StringBuilder() for i in 1..times do sb.Append(text) |> ignore sb.ToString() 

If you want to remove trailing spaces, as in your example, you can use the Trim() member in the String class to do this.

+12
source

If you need a clean, do-it-yourself functional version for F # training purposes, then something like the following snippet will do:

 let myFunc times text = let rec grow result doMore = if doMore > 0 then grow (result + text) (doMore- 1) else result grow "" times 

Here is the test:

 > myFunc 3 "test";; val it : string = "testtesttest" 

Otherwise, you should follow the pointer to the standard F # replicate library function specified in the pad response.

+2
source

The pad's solution, given that it's just a fold:

 let multiply n (text: string) = (StringBuilder(), {1..n}) ||> Seq.fold(fun b _ -> b.Append(text)) |> sprintf "%O" 
+2
source

String.replicate already provides the functionality you are looking for.

If for some reason you want to change the arguments, you can do it like this:

 (* A general function you should add to your utilities *) let flip fab = fba let myFunc = flip String.replicate 
+1
source

In a simple recursive form:

 let rec dupn = function |s,1 -> s |s,n -> s ^ dupn(s, n-1) 
0
source

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


All Articles