【问题标题】:How to code recursive string other parameter in Ocaml如何在 Ocaml 中编写递归字符串其他参数
【发布时间】:2019-03-17 14:43:50
【问题描述】:

我想像string(2^n) 这样编码。

例如。

let string2 s = 
    match s with
    " " -> " "
    | _ -> s^s;;   

但是,

let rec string128 s = 
    match s with 
      " " -> " " 
    | _ -> string128 s^s ;;

它有溢出。如何仅使用递归函数进行编码? 我不想使用其他参数。比如`n -> n-1'

如果我在 string128 中输入 'a' 然后重复 'a' 128 次。

【问题讨论】:

  • 它“溢出”,因为任何字符串与自身的连接都不会产生" " 的基本情况,因此它将无限递归。否则不清楚您要做什么,因为“喜欢string(2^n)”没有任何意义。如果您可以提供一些函数的输入和预期输出示例,则可能会破译您想要完成的任务,但否则您必须实际尝试解释它。
  • 如果我在 string128 中输入“a”,然后重复 'a' 128 次。这就是我想做的。
  • 好吧,这更有意义。您能否更新您的问题以包含该示例?
  • 我做到了。在基本情况下我应该改变什么?
  • 我可能理解的不好,但是你为什么不想使用另一个参数呢?你的字符串是常数,它没有其他信息可以用来知道你的递归函数何时停止?

标签: recursion functional-programming ocaml


【解决方案1】:

我不确定你为什么不想使用额外的参数,但你可以使用字符串的长度作为终止条件。由于不清楚你想对包含多个字符的初始字符串做什么,这里有两个可能的版本:

let rec string128 s = if String.length s >= 128 then s else string128 (s^s);;

 let string128bis s =
   let orig_length = String.length s in
   let rec aux s =
     if String.length s >= 128 * orig_length then s else aux (s^s)
   in aux s;;

string128 将连接字符串,直到结果至少有 128 个字符宽。 string128bis 将等待结果字符串比原始输入长 128 倍。 string128 "a"string128bis a 都将返回 128 a,但 string128 "abcd" 将返回重复 abcd 的 128 个字符的字符串,而 string128bis "abcd" 的长度为 512 个字符。

【讨论】:

    猜你喜欢
    • 2015-05-12
    • 2018-03-04
    • 1970-01-01
    • 2017-02-27
    • 2020-10-24
    • 2012-04-03
    • 2023-04-05
    • 2014-03-28
    • 1970-01-01
    相关资源
    最近更新 更多