F#分割清单

时间:2018-11-25 20:17:35

标签: list f# match

我正在学习一种新的编程语言,它是F#,我正在努力解决一种方法。我需要将电影和书籍列表分为2个列表。一个是放电影的地方,另一个是放书的地方。我不能使用F#中已经存在的功能。我将一些示例链接到现在为止。预先谢谢你

type Movie =
{ movieName: string
  duration: Nat
  fileSize: Nat }

type Book =
    { bookName: string
      pages: Nat }

type Activity =
    | Watch of Movie
    | Read of Book

let rec partitionActivities(activities: Activity list): (Book list * Movie list) = 
  match activities with
  | [] -> [],[]
  | x::_ -> match x with
    | Read Book -> [Book],[]
    | Watch Movie -> [],[Movie]
  | _::xs -> partitionActivities(xs)

我的输入是什么:

partitionActivities [
                    Read { bookName = "A"; pages = 45N }
                    Watch { movieName = "B"; duration = 120N; fileSize = 50N }
                    Read { bookName = "C"; pages = 700N }
                    Watch { movieName = "D"; duration = 100N; fileSize = 1024N }
                    Watch { movieName = "E"; duration = 150N; fileSize = 9001N }
                    Read { bookName = "F"; pages = 700N }

结果应该是:

[
                    { bookName = "A"; pages = 45N }
                    { bookName = "C"; pages = 700N }
                    { bookName = "F"; pages = 700N }
                ], [
                    { movieName = "B"; duration = 120N; fileSize = 50N }
                    { movieName = "D"; duration = 100N; fileSize = 1024N }
                    { movieName = "E"; duration = 150N; fileSize = 9001N }
                ]

1 个答案:

答案 0 :(得分:0)

那是正确的想法。用列表的末尾(xs)进行递归,取当前的Activity,确定是涉及Movie还是Book,然后将其添加到对应的列表的前面列出并返回两个列表:

let rec partitionActivities(activities: Activity list): (Book list * Movie list) = 
  match activities with
  | [] -> [], []
  | x::xs -> 
    let books, movies = partitionActivities(xs)
    match x with
    | Read book -> book::books, movies
    | Watch movie -> books, movie::movies