Multiplying a string in F#

旧时模样 提交于 2020-01-04 01:58:13

问题


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?


回答1:


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.




回答2:


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.




回答3:


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"



回答4:


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



回答5:


In a simple recursive fashion:

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


来源:https://stackoverflow.com/questions/9112485/multiplying-a-string-in-f

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