简体   繁体   中英

remove type from type list haskell

So i'm new to Haskell, and I was wondering if anyone could help me.

I've got a list of a custom data type like so:

type Title = String
type Manager = String
type Year = Int
type Fan = String
type Album = (Title, Manager, Year, [Fan])

And I have a pre-made static database of albums

albumDatabase :: [Album]
albumDatabase = [(...)]

And I have a function that returns all albums that a manager has made:

manAlbum :: String -> [Album] -> [Album]
manAlbum d database = filter ((\(_,album,_,_) -> d == album)) database

My question is, from this new list of all the managers albums, I need to retrieve only the fans and drop the Title, Manager and Year. However I am unsure of how to tell haskell that I only want this field from the custom datatype to be returned.

As 4castle mentioned, you can use map :

getAlbumFans :: [Album] -> [[Fan]]
getAlbumFans database = map (\(_,_,_,fans) -> fans) database

Also you could make the manAlbum function more readable by giving it a more descriptive name like getAlbumsByManager and replacing String in the type signature with Manager .

Another solution might be to make Album an algebraic data type. I guess that the code might be easier to understand, when rewritten as follows:

type Title = String
type Manager = String
type Year = Int
type Fan = String
data Album = Album { title :: Title, manager :: Manager, year :: Year, fans :: [Fan]} deriving (Show)

albumDatabase :: [Album]
albumDatabase = [Album {title="A", manager="B", year=5, fans=["a","b"]}]

check :: Album -> String -> Bool
check a d=title a==d

manAlbum :: String -> [Album] -> [[Fan]]
manAlbum d database = map (\a->fans a) $ filter (\a->title a==d) database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM