如何处理 OCAML 列表的元素?

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

我想处理文件“persons.txt”中存在的数据。 但我已经尝试了一切来处理文本文件中的所有行。

我处理数据的唯一方法是手动创建列表。

let myList = ["John"; "23"]

我希望程序迭代文本文件的所有行。 我已经设法将文本文件的所有内容传递到列表中,但我似乎无法从该阶段继续前进。

我的想法是:

  1. 从文本文件中读取内容
  2. 转换为 OCaml 列表
  3. 将列表分成子列表
  4. 遍历子列表
  5. 仅打印到符合条件的屏幕文本

你能指导我吗?

谢谢!!

open Printf

(* FILE CONTENTS *)
(*
John;23;
Mary;16;
Anne;21;
*)

let file = "data/persons.txt"
;;

(* READ FROM EXTERNAL FILE *)
let read_lines name : string list =
  if Sys.file_exists (name) then
    begin
      let ic = open_in name in
      try
        let try_read () =
          try Some (input_line ic) 
          with End_of_file -> None 
        in
        let rec loop acc = 
          match try_read () with
          | Some s -> loop (s :: acc)
          | None -> close_in_noerr ic; List.rev acc 
        in
        loop []
      with 
        e -> close_in_noerr ic;[]
    end
  else
    []
;;

(...)
list ocaml
1个回答
1
投票

你的问题根本不明确。以下是一些观察结果:

首先,您的

read_lines
函数不会以您需要的形式返回输入。

read_lines
返回的内容如下所示:

["John;23;"; "Mary;16;"; "Anne;21;"]

但是你想要的更像是这样的:

[(“约翰”,“23)”; (“玛丽”,“16”); (“安妮”,“21”)]

这里的关键是使用

;
作为分隔符将字符串分成几部分。您可以使用
String.split_on_char
来实现此目的。

其次,您没有定义一个函数来根据参数计算答案。相反,您的计算基于全局变量。这不能一概而论。

而不是这样说:

 let adult_check_condition = 
     ... using global age and name ...

你需要定义一个函数:

let adult_check_condition age name =
     ... use parameters age and name ...

然后你可以用不同的年龄和名字来调用这个函数。

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