Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying a string in F#

Tags:

string

f#

I have a question I am rather unsure about.

My questions is as follows

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

What I want this function to do is put the string together as many times as specified by the times parameter.

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

I have tried with a loop, but couldn't seem to make it work.

Anyone?

like image 451
user1090614 Avatar asked Feb 02 '12 12:02

user1090614


3 Answers

Actually the function is already in String module:

let multiply text times = String.replicate times text

To write your own function, an efficient way is using 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 whitespaces as in your example, you can use Trim() member in String class to do so.

like image 64
pad Avatar answered Oct 12 '22 21:10

pad


If you want a pure functional "do-it-yourself" version for F# learning 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 about the standard F# library function replicate given in pad's answer.

like image 37
Gene Belitski Avatar answered Oct 12 '22 21:10

Gene Belitski


A variation on 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"
like image 25
Daniel Avatar answered Oct 12 '22 20:10

Daniel