22

我想编写一个接受字符串并返回字符列表的函数。这是一个函数,但我认为它不是我想要的(我想获取一个字符串并返回一个字符列表)。

let rec string_to_char_list s =
    match s with
      | "" -> []
      | n -> string_to_char_list n
4

6 回答 6

31

除了,但非常重要:

您的代码显然是错误的,因为您有一个递归调用,其所有参数都与您输入的完全相同。它将引发具有相同值的无限调用序列,因此永远循环(堆栈溢出不会' t 发生在 tail-rec 位置)。


做你想做的代码是:

let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []

资料来源: http ://caml.inria.fr/pub/old_caml_site/FAQ/FAQ_EXPERT-eng.html#strings


或者,您可以选择使用库:电池String.to_list或 extlib String.explode

于 2012-04-09T06:56:16.267 回答
21

尝试这个:

let explode s = List.init (String.length s) (String.get s)
于 2018-09-18T18:49:50.177 回答
5

很好很简单:

let rec list_car ch = match ch with
    | "" -> []
    | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;
于 2014-06-12T00:03:17.250 回答
3

像这样的东西怎么样:

let string_to_list str =
  let rec loop i limit =
    if i = limit then []
    else (String.get str i) :: (loop (i + 1) limit)
  in
  loop 0 (String.length str);;

let list_to_string s =
  let rec loop s n =
    match s with
      [] -> String.make n '?'
    | car :: cdr ->
       let result = loop cdr (n + 1) in
       String.set result n car;
       result
  in
  loop s 0;;
于 2015-08-10T21:47:12.320 回答
1

这是从字符串中获取字符列表的迭代版本:

let string_to_list s = 
let l = ref [] in
for i = 0 to String.length s - 1 do
    l := (!l) @ [s.[i]]
done;
!l;;
于 2018-12-18T11:01:25.310 回答
1

我的代码,适用于现代 OCaml:

let charlist_of_string s =
  let rec trav l i =
    if i = l then [] else s.[i]::trav l (i+1)
  in
  trav (String.length s) 0;;

let rec string_of_charlist l =
  match l with
    [] -> "" |
    h::t -> String.make 1 h ^ string_of_charlist t;;
于 2020-09-28T15:09:41.020 回答