Ocaml流函数

问题描述 投票:-1回答:1

我正在尝试创建一个函数,以某种方式从文件中读取所有行,然后将其打印出来。

这是我到目前为止的去处:

let read file =
  let rec create_list new_list =
    match Stdio.In_channel.input_line file with
    | Some(line)  -> create_list ((format_line line) :: new_list)
    | None  -> List.rev new_list
  in
  create_list []

在匹配项[[format_line x内部调用的函数具有以下类型:

val format_line : string -> string * string
我对

读取文件

函数的目标是获得这种类型的东西: val read: In_channel -> (string,string) list
经过编译和测试后,我发现它可以完成我想做的所有事情。这是我的主要样子:

let () = In_channel.create (Sys.get_argv()).(1) |> read |> List.iter ~f:(fun (f,c) -> printf "%s %s \n" f c )

问题是,我被告知必须先打印出整个列表,然后才能打印出来,要使用这种类型来重写函数:

type 'a stream = Nil | Cons of 'a * 'a stream thunk and 'a thunk = unit -> 'a

我显然也必须更改List.iter函数,但我只想知道如何将

读取文件

变成这种类型的函数:val read : In_channel -> (string*string) stream
functional-programming stream ocaml ocamlbuild
1个回答
0
投票
我不确定我是否正确理解了您的问题,但是能否告诉我以下代码:

let read file = Stdio.In_channel.input_lines file |> List.map format_line

满足您的需求吗?如果没有,还缺少什么?

编辑:哦,是的,那不是您要的,抱歉。您不希望有一个庞大的列表可以一次在内存中维护所有行。好。那这样的东西呢?

let rec read file = match Stdio.In_channel.input_line file with | Some line -> Cons (format_line line, fun () -> read file) | None -> Nil

© www.soinside.com 2019 - 2024. All rights reserved.