问题
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