【问题标题】:Convert a char list list into a char string list in OCAML在 OCAML 中将 char 列表列表转换为 char 字符串列表
【发布时间】:2018-07-22 23:34:09
【问题描述】:

我有一个例子:

val lst1 : char list list =
  [['l'; 'a'; 'n'; 'e']; ['p'; 'l'; 'a'; 'n'; 'e'; 't']; ['m'; 'o'; 'o'; 't'];
   []; []; ['s'; 'm'; 'o'; 'o'; 't'; 'h']; ['h'; 'a'; 'n'; 'g']; []; 
   []; ['c'; 'h'; 'a'; 'n'; 'g'; 'e']; ['w'; 'e'; 'n'; 't']; []; []; etc.]

将这个列表转换成类似的东西有什么技巧:

["lane";"planet";...]?

谢谢。

【问题讨论】:

  • 如果你想知道为什么你的投票被否决了,这可能是因为这看起来很像家庭作业,并且没有任何迹象表明你有任何努力去解决它。大多数人认为你应该自己做功课。毕竟,这似乎是它的重点。请参阅How to Ask
  • 最好的讲师知道如何在不给出解决方案的情况下将信息传递给技术水平较低的人。这就是我提问的目的。我很高兴我没有在上面的问题中使用“我需要解决方案”。谢谢!
  • 您仍然需要努力自己解决问题,并就具体问题提出问题。请参阅此处的第 3 点stackoverflow.com/help/on-topic“请求家庭作业帮助的问题必须包括您迄今为止为解决问题所做的工作的总结,以及您在解决问题时遇到的困难的描述。”我>

标签: list char ocaml


【解决方案1】:

这是一个非常紧凑的实现:

let to_str_list =
  List.map (fun cs -> String.concat "" (List.map (String.make 1) cs))

当你调用它时它看起来像这样:

# to_str_list [['h';'e';'l';'l';'o'];['w';'o';'r';'l';'d']];;
- : string list = ["hello"; "world"]

更新

如果你想在外层抑制空字符串,你可以这样做:

let to_str_list css =
  List.map (fun cs -> String.concat "" (List.map (String.make 1) cs)) css |>
  List.filter ((<>) "")

当你调用它时它看起来像这样:

# to_str_list [['h';'e';'l';'l';'o']; []; ['w';'o';'r';'l';'d']];;
- : string list = ["hello"; "world"]

【讨论】:

  • 在我的输出中,有很多“”。有没有办法消除它?谢谢!
【解决方案2】:

应该这样做,

let to_string l =
  let rec loop buf = function
    | [] -> Buffer.contents buf
    | x :: tl -> Buffer.add_char buf x; loop buf tl
  in
  loop (Buffer.create 100) l

let to_str_lst l = List.map to_string l

不带recto_string 的替代版本-

let to_string l =
  List.fold_left
    (fun acc e -> Buffer.add_char acc e; acc)
    (Buffer.create 100)
    l
  |> Buffer.contents

utop 中的示例用法:

to_str_lst [['h';'e';'l';'l';'o']; ['w';'o';'r';'l';'d']];;

返回

- : string list = ["hello"; "world"]

【讨论】:

  • 我可以不使用rec吗?
  • 当然。你可以在 to_string() 函数中使用 List.fold_left 来实现 loop()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多