我正在嘗試遍歷Sexp.t
Jane Street Sexplib 模塊中定義的資料型別。我想以顯示其遞回結構以進行除錯的方式列印出資料型別。到目前為止,這就是我所擁有的:
type sexp =
| Atom of string
| List of sexp list
(* pretty prints an sexp *)
let rec to_str (se : sexp) : string =
match se with
| Atom s -> s
| List [] -> ""
| List (hd :: tl) -> to_str hd ^ to_str (List tl)
let () =
let se = List [Atom "a"; List [Atom "b"; Atom "c"]; Atom "d"; Atom "e"] in
print_endline (to_str se)
輸出是abcde
一個扁平串列。我希望將其列印為類似于:
List [Atom "a"; List [Atom "b"; Atom "c"]; Atom "d"; Atom "e"]
我做了一些嘗試,很快就變得一團糟。我只是不確定遞回案例應該是什么樣子。有人可以幫我嗎?
uj5u.com熱心網友回復:
這不是很有效,但對您的功能所做的更改很少,并且應該很容易理解:
let rec to_str (se : sexp) : string =
match se with
| Atom s -> Printf.sprintf "Atom \"%s\"" s
| List [] -> ""
| List items ->
let items = items |> List.map to_str |> String.concat "; " in
Printf.sprintf "List [%s]" items
哪個列印
List [Atom "a"; List [Atom "b"; Atom "c"]; Atom "d"; Atom "e"]
它Printf.sprintf
使用方便,但如果您愿意,仍然可以使用純字串連接。可以改用更高效的版本Format.fprintf
。
uj5u.com熱心網友回復:
@glennsl 提供的答案很棒,但讓我們看看你的代碼在做什么,看看為什么它會給你看到的結果。
let rec to_str (se : sexp) : string = match se with | Atom s -> s | List [] -> "" | List (hd :: tl) -> to_str hd ^ to_str (List tl)
然后,您評估to_str se
where se
is List [Atom "a"; List [Atom "b"; Atom "c"]; Atom "d"; Atom "e"]
。
to_str (List [Atom "a"; List [Atom "b"; Atom "c"]; Atom "d"; Atom "e"])
to_str (Atom "a") ^ to_str (List [List [Atom "b"; Atom "c"]; Atom "d"; Atom "e"])
"a" ^ (to_str (List [Atom "b"; Atom "c"]) ^ to_str (List [Atom "d"; Atom "e"]))
"a" ^ (to_str (Atom "b") ^ to_str (List [Atom "c"]))
^ (to_str (Atom "d") ^ to_str (List [Atom "e"]))
"a" ^ ("b" ^ (to_str (Atom "c") ^ to_str (List [])))
^ ("d" ^ (to_str (Atom "e") ^ to_str (List [])))
"a" ^ ("b" ^ ("c" ^ ""))
^ ("d" ^ ("e" ^ ""))
"a" ^ ("b" ^ "c") ^ ("d" ^ "e")
"a" ^ "bc" ^ "de"
"abcde"
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430274.html
上一篇:如何根據Python中的不同鍵從字典串列中查找最大值
下一篇:有條件的字典串列到一個字典中