user1090614
user1090614

Reputation: 2687

Multiplying a string in 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?

Upvotes: 10

Views: 3593

Answers (5)

missingfaktor
missingfaktor

Reputation: 92026

String.replicate already provides the functionality you're looking for.

If for some reason you want the arguments reversed, you can do it as follows:

(* A general function you should add to your utilities *)
let flip f a b = f b a
 
let myFunc = flip String.replicate

Upvotes: 2

pad
pad

Reputation: 41290

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.

Upvotes: 24

Daniel
Daniel

Reputation: 47904

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"

Or use String.replicate from F# standard's lib.

Upvotes: 3

Aphex
Aphex

Reputation: 408

In a simple recursive fashion:

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

Upvotes: -1

Gene Belitski
Gene Belitski

Reputation: 10350

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.

Upvotes: 2

Related Questions