Haskell - 有选择地添加列表 [英] Haskell - Selectively Adding Lists

查看:117
本文介绍了Haskell - 有选择地添加列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  type Rating =(String,Int)
type Film =(String ,String,Int,[Rating])

testDatabase :: [Film]
testDatabase = [(Director 1,Film 1,2012,[(TestRat,8 )]),(导演2,电影2,2,[])]

我需要找出导演的平均评分是基于他们所有电影的总和,然后将他们的所有评分结合起来。我真的不知道该如何解决这个问题,我发现仅仅为了获得电影中元组的平均值就够困难了,更不用说通过它们来完成所有这些操作。



用于计算平均值的代码:

  filmRating :: [(String,Int)]  - > Float 
filmRating rating = average(map snd ratings)

average ratings = realToFrac(sum ratings)/ genericLength ratings


解决方案

Data.List 进行数据分析。

groupBy 非常有用:

 > :t groupBy 
groupBy ::(a - > a - > Bool) - > [a] - > [[a]]

给定一个相等函数,将一个列表分组到桶中。 b
$ b

访问目录的函数:

 >让fst4(x,_,_,_)= x 

然后,以及由该导演制作的群组(group)。

 >让db0 = sortBy(比较fst4)testDatabase 
>让db1 = groupBy((== ==``on` fst4)db0
[[(Director 1,Film 1,2012,[(TestRat,8)])]
, [(导演2,电影2,2,[])]
]

groupBy 非常有用...


I have the following type:

type Rating = (String, Int)
type Film = (String, String, Int, [Rating])

testDatabase :: [Film]
testDatabase = [("Director 1","Film 1",2012,[("TestRat",8)]),("Director 2","Film 2",2,[])]

I need to find out what the average rating of the Director is based on all of their films combined and then all of their ratings combined. I genuinely have no idea how to approach this, I found it hard enough just to get the average of the tuples in the Film let alone work through all of them and do it that way.

My code for working out averages:

filmRating :: [(String,Int)] -> Float
filmRating ratings = average (map snd ratings)

average ratings = realToFrac (sum ratings) / genericLength ratings  

解决方案

There are many useful functions in Data.List for data analysis.

In particular, groupBy is super useful:

> :t groupBy
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]

Given an equality function, group a list into buckets.

A function to access the directory:

 > let fst4 (x,_,_,_) = x

Then, sort on the director name, and bucket (group) by that director.

 > let db0 = sortBy (comparing fst4) testDatabase
 > let db1 = groupBy ((==) `on` fst4) db0
 [ [("Director 1","Film 1",2012, [("TestRat",8)])]
 , [("Director 2","Film 2",2    ,[])]
 ]

groupBy is very useful...

这篇关于Haskell - 有选择地添加列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆