使用List.fold_left的OCaml concat stringlist

时间:2012-10-26 09:30:55

标签: ocaml

我在基础和f和l函数中遇到了一些错误,我错了什么?

该功能应该做的例子是。

# sepConcat ", " ["foo";"bar";"baz"];;
- : string = "foo, bar, baz"

# sepConcat "---" [];;
- : string = ""

# sepConcat "" ["a";"b";"c";"d";"e"];;
- : string = "abcde"

# sepConcat "X" ["hello"];;
- : string = "hello" 

老师给了我这个我应该填写的代码。

let rec sepConcat sep s1 = match s1 with
  |[] -> ""
  |h::t -> 
        let f a x = failwith "to be implemented" in
    let base = failwith "to be implemented" in
    let l = failwith "to be implemented" in
        List.fold_left f base l

我到目前为止

let rec sepConcat sep s1 = match s1 with
  |[] -> ""
  |h::t -> 
        let f a x = a^sep^x in
    let base = 0 in
    let l = sepConcat sep t in
        List.fold_left f base l

2 个答案:

答案 0 :(得分:2)

您的代码出现的错误如下,指向代码中的base

Error: This expression has type int but an expression was expected of type
       string

这是什么意思?问题是什么?你是如何解决的?

另一个问题是你sepConcat的递归调用。你在使用fold_left还是在编写递归函数?如果你正在做其中一件事,你就不需要做另一件事了。

答案 1 :(得分:1)

这是使用fold_left和可选参数的实现:

let concat ?(sep="") l =
  List.fold_left (fun acc e -> acc^sep^e) (List.hd l) (List.tl l);;
val concat : ?sep:bytes -> bytes list -> bytes = <fun>

这是另一个使用尾递归函数的实现:

let concat ?(sep="") l =
  let rec loop acc = function
    | [] -> acc
    | h::t -> loop (acc^sep^h) t
  in
  loop (List.hd l) (List.tl l);;
val concat : ?sep:bytes -> bytes list -> bytes = <fun>

两者的行为方式完全相同:

concat ~sep:(" ") ["hello"; "world"];;
- : bytes = "hello world"