F#分割清单 [英] F# divide lists
问题描述
我正在学习一种新的编程语言,它是F#,我正在努力解决一种方法.我需要将电影和书籍的列表分为2个列表.一个是放电影的地方,另一个是放书的地方.我不能使用F#中已经存在的功能.我将一些示例链接到现在为止.预先谢谢你
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)
我的输入是什么:
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 }
]
推荐答案
那是正确的想法.用列表的尾部(xs
)进行递归,获取当前的Activity
,确定它是否包含Movie
或Book
,将其添加到相应列表的前面,并返回两个列表:>
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
这篇关于F#分割清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!