AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79141312
Accepted
Marceau
Marceau
Asked: 2024-10-30 21:30:23 +0800 CST2024-10-30 21:30:23 +0800 CST 2024-10-30 21:30:23 +0800 CST

我怎样才能使这个表达式成为字符串类型而不是字符串->字符串?

  • 772

我正在学习 OCaml,在函数式编程方面遇到了一些麻烦......

我需要创建一个函数,用于替换给定整数列表的字符,即字符串中该索引处的字符。例如,我输入 [1;4] 'u'“Hello”,它输出“Hullu”。

这就是我想出的:

let remplace_positions lst c str =
  let rec acc lst c str n l_index ret =
    match (n >= String.length str, List.nth lst l_index = n) with 
    | true, _ -> ret
    | _, true -> acc lst c (n+1) (l_index+1) (ret ^ (String.make 1 c))
    | _, _ -> acc lst c (n+1) (l_index+1) (ret ^ (String.make 1 (String.get str n)))
  in 
  acc lst c str 0 0 ""

但如您所见,最后两个匹配案例存在错误。它们是字符串 -> 字符串类型,但我希望它们是字符串类型。

有人知道如何在递归调用函数时修复这个问题吗?

functional-programming
  • 1 1 个回答
  • 38 Views

1 个回答

  • Voted
  1. Best Answer
    Chris
    2024-10-30T22:49:23+08:002024-10-30T22:49:23+08:00

    当我测试你的功能时,我得到:

    # let remplace_positions lst c str =
      let rec acc lst c str n l_index ret =
        match (n >= String.length str, List.nth lst l_index = n) with
        | true, _ -> ret
        | _, true -> acc lst c (n+1) (l_index+1) (ret ^ (String.make 1 c))
        | _, _ -> acc lst c (n+1) (l_index+1) (ret ^ (String.make 1 (String.get str n)))
      in
      acc lst c str 0 0 "";;
    Error: This expression has type int
           but an expression was expected of type string
    

    参照(n+1)以下行:

        | _, true -> acc lst c (n+1) (l_index+1) (ret ^ (String.make 1 c))
    

    这是因为您已指出第三个参数acc应该是string,但随后您传递了一个int。

    我认为你传递了太多参数acc,这让跟踪它们变得很困难。如果它们没有改变,内部函数就没有必要将它们作为参数。内部函数将能够从外部作用域访问绑定,只要它们没有被遮蔽。

    我们还可以分解出将字符转换为字符串。

    let remplace_positions lst c str =
      let char_to_str c = String.make 1 c in
      let rec acc str n l_index ret =
        match (n >= String.length str, List.nth lst l_index = n) with
        | true, _ -> ret
        | _, true -> acc (n+1) (l_index+1) (ret ^ char_to_str c)
        | _, _ -> acc (n+1) (l_index+1) (ret ^ char_to_str (String.get str n))
      in
      acc str 0 0 ""
    

    同样的错误,但是代码更容易阅读。

    现在,让我们删除不必要的str参数传递:

    let remplace_positions lst c str =
      let char_to_str c = String.make 1 c in
      let rec acc n l_index ret =
        match (n >= String.length str, List.nth lst l_index = n) with
        | true, _ -> ret
        | _, true -> acc (n+1) (l_index+1) (ret ^ char_to_str c)
        | _, _ -> acc (n+1) (l_index+1) (ret ^ char_to_str (String.get str n))
      in
      acc 0 0 ""
    

    现在它编译成功了。让我们运行它。

    # remplace_positions [1; 4] 'u' "hello";;
    Exception: Failure "nth".
    

    到底哪里出了问题?

    好吧,让我们来追溯一下:

    remplace_positions [1; 4] 'u' "hello"
    
    acc 0 0 ""
      n >= String.length "hello" -> false
      List.nth [1; 4] 0 = n -> false
    acc 1 1 ("" ^ "h")
      n >= 5 -> false
      List.nth [1; 4] 1 = n -> false
    acc 2 2 ("h" ^ "e")
      n >= 5 -> false
      List.nth [1; 4] 2 = n -> exception!
    

    您已将列表索引增加到尝试访问超出范围的列表的程度,从而导致异常。

    说实话,你的基本方法不值得保留。List.nth即使成功使用也是低效的,因为它是 O(n) 操作,而不是 O(1)。

    您最终需要做的是迭代列表,并将每个索引处的字符替换为您指定的字符。列表上的模式匹配提供了完成列表迭代的最惯用方法。

    let rec replace_chars lst c str =
      let len = String.length str in
      let cs = String.make 1 c in
      match lst with
      | [] -> str
      | hd::tl ->
        let front_of_str = String.sub str 0 hd in
        let tail_of_str = String.sub str (hd + 1) (len - hd - 1) in
        replace_chars tl c (front_of_str ^ cs ^ tail_of_str)
    

    但在 OCaml 中,字符串是不可变的,这会让事情变得很混乱。获取子字符串并将它们重新连接在一起确实占用了大量空间。如果它们是可变的,那就更容易了。

    幸运的是,Bytes模块就是为此而设计的。我们可以将其转换为可变bytes类型,对其进行修改,然后再转换回string。

    let replace_chars lst c str =
      let b = Bytes.of_string str in
      let rec aux lst =
        match lst with
        | [] -> b
        | hd::tl -> (Bytes.set b hd c; aux tl)
      in
      String.of_bytes (aux lst)
    

    但实际上,遍历列表并对每个元素应用操作已经由 处理了List.iter。

    let replace_chars lst c str =
      let b = Bytes.of_string str in
      List.iter (fun i -> Bytes.set b i c) lst;
      String.of_bytes b
    
    • 0

相关问题

  • 在 Enumerable Protocol 官方文档中找到的下面的 Elixir 代码中每个枚举的 acc 和 x 中的值是什么?

  • `max` 的输出是什么

  • Agda 证明 Bool ≢ ⊤

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve