以F#次数连接字符串 [英] Concatenating strings in F# number of times

查看:59
本文介绍了以F#次数连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串连接一定的时间,但是我觉得我已经通过使用高阶函数作了一些欺骗(或者至少没有真正理解应该怎么做):

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

显然是给我的 aaaaaaaaaa,但是如果没有高阶函数怎么办呢?我觉得这是一个非常简单的问题,但我似乎无法解决这个问题,F#语法或思维方式对我来说仍然很麻烦。

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.

推荐答案

如果您只想使用递归解决方案,怎么办?

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

或采用if表达式的更经典样式:

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

这篇关于以F#次数连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆