我想通过提示用户输入来构建字符串列表。我的最终目标是能够使用简单的例程针对简单的哈希表解析字符串列表。
`let list_find tbl ls =
List.iter (fun x ->
let mbr = if Hashtbl.mem tbl x then "aok" else "not found"
in
Printf.printf "%s %s\n" x mbr) ls ;;`
使用cons运算符::来构建字符串列表,但不知怎的,我无法获得生成字符串列表的提示。 simpe list函数返回以列表形式放入的任何内容:
`let build_strlist x =
let rec aux x = match x with
| [] -> []
| hd :: tl -> hd :: aux tl
in
aux x ;;`
到目前为止,我已经能够设置提示符,但是构建字符串列表并不是那么顺利。我倾向于认为我应该使用Buffer或Scanning.in_channel。这就是我到目前为止所做的:
`#load "unix.cma" ;;
let prompt () = Unix.isatty Unix.stdin && Unix.isatty Unix.stdout ;;
let build_strlist () =
let rec loop () =
let eof = ref false in
try
while not !eof do
if prompt () then print_endline "enter input ";
let line = read_line () in
if line = "-1" then eof := true
else
let rec build x = match x with
| [] -> []
| hd :: tl -> hd :: build tl
in
Printf.printf "you've entered %s\n" (List.iter (build line));
done
with End_of_file -> ()
in
loop () ;;`
我收到一个错误,关键字“line”具有类型字符串,但表达式需要类型为“列表”。我应该使用Buffer.create buf构建字符串列表,然后使用Buffer.add_string buf prepending [后跟引号“another”和分号?这似乎是一种矫枉过正。也许我应该只返回一个字符串列表并忽略任何“窥视我们所拥有的”的尝试?检查哈希表后将进行打印。
我想有一个提示例程,以便我可以使用ocaml进行脚本编写和用户交互。我发现了一些在线的想法,这让我可以写上面的骨架。
答案 0 :(得分:0)
我可能会在几个步骤中解决问题:
第一步可以使用递归函数实现,如下所示:
let build_strlist' () =
let rec loop l =
if prompt () then (
print_string "enter input: ";
match read_line () with
"-1" -> l
| s -> loop (s::l)
) else l
in loop [];;
了解该函数如何循环自身并构建列表l
。正如您在评论中提到的,我删除了代码的命令部分,仅保留功能递归。您可以通过保留命令性部分并省略递归来实现相同目的,但递归对我来说更自然,如果written correctly导致大多数相同的机器代码。
获得列表后,只需使用临时打印功能对List.iter
应用{{1}},就像在原始函数中一样。