Adam
Adam

Reputation: 1699

How can I link these two Haskell functions together?

I am trying to remove a certain actor from a list of actors as there are duplicates. I have these functions that do what i want but i need them to link. The two functions that i need to link are createWholeActorList and removeAllActor.

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

If this way is complicated, is there a way of using list comprehension to achieve the desired result?

Upvotes: 0

Views: 97

Answers (1)

madjar
madjar

Reputation: 12951

If the desired effect is to remove duplicates from a list, it might be easier (and result in faster code) to use a Set. A set is a data structure that can contain each item only once. So, to remove duplicates in a list, you can simply convert it to a set and back again to a list.

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

Then, createActorList can be defined as

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

Or, without createWholeActorList

createActorList = removeDuplicates . concat . actorsInFilm

Upvotes: 1

Related Questions