如何将这两个Haskell函数链接在一起?

时间:2015-03-17 10:46:06

标签: list haskell

我正试图从演员列表中删除某个演员,因为有重复项。我有这些功能做我想要的但我需要他们链接。我需要链接的两个功能是createWholeActorListremoveAllActor

type Actor = String
type Actors = [Actor]

showActors :: Film -> Actors --Outputs a list of the Actors in the film
showActors (_,a,_,_) = a

actorsInFilm :: Actor -> [Actors]
actorsInFilm actor = map showActors (filmsActorIsIn actor)

createWholeActorList :: Actor -> Actors
createWholeActorList actor = concat (actorsInFilm actor)

removeAllActor :: Actor -> Actors -> Actors
removeAllActor _ [] = []
removeAllActor actor (head:tail)
    | head == actor = removeAllActor actor tail
    | head /= actor = head : removeAllActor actor tail

如果这种方式很复杂,有没有办法使用列表理解来达到预期的效果呢?

1 个答案:

答案 0 :(得分:1)

如果所需的效果是从列表中删除重复项,则使用Set可能更容易(并且导致更快的代码)。集合是一种数据结构,只能包含每个项目一次。因此,要删除列表中的重复项,您只需将其转换为集合,然后再将其转换为列表。

import Data.Set (Set)
import qualified Data.Set as Set
removeDuplicates :: Ord a => [a] -> [a]
removeDuplicates = Set.toList . Set.fromList

然后,createActorList可以定义为

createActorList :: Actor -> [Actor]
createActorList = removeDuplicates . createWholeActorList

或者,没有createWholeActorList

createActorList = removeDuplicates . concat . actorsInFilm