F# divide lists

╄→尐↘猪︶ㄣ 提交于 2019-12-24 11:22:43

问题


i'm learning a new programming language, which is F# and I'm struggling to solve a method. I need to divide a list of movies and books into to 2 lists. One where the movies are and another one where the books are listed in. I can't use functions that already exists in F#. I link some exemples what i have done until now. Thank you in advance

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)

What my inputs are :

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 }

What result should be :

[
                    { 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:


That is the right idea. Recurse with the tail of the list (xs), take the current Activity, determine if it involves a Movie or a Book, add it to the front of the corresponding list and return both lists:

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


来源:https://stackoverflow.com/questions/53471526/f-divide-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!