2017-11-04 2 views
0

ArtistGenre 문자열을 매개 변수로 허용하는 함수를 작성하려고 시도하고 해당 장르의 모든 Artist을 출력합니다. 다음과 같이 나는 데이터 유형 Artist을 정의했습니다 :사용자 정의 형식 필터링

data Artist = Artist Name Genres 
    deriving Show 
type Name = String 
type Genres = [Genre] 
type Genre = String 

다음과 같은 기능을 구현하는 내 코드는 다음과 같습니다

getFilteredArtists :: [Artist] -> Genre -> [Artist] 
getFilteredArtists xs genre = filter (genre) (map getGenres xs) 

샘플 함수 호출은 다음과 같습니다 :

artists = [ 
    Artist "Grimes" ["Electropop", "Dream Pop", "Synthpop"], 
    Artist "My Bloody Valentine" ["Shoegaze", "Noise Pop", "Post Punk"], 
    Artist "David Bowie" ["Art Rock", "Pop Rock", "Glam Rock", "New Wave"] 
    ] 

getFilteredArtists artists "Art Rock" 

어느해야 return [Artist "David Bowie" ["Art Rock", "Pop Rock", "Glam Rock", "New Wave"]

그러나 내 기능은 typ를 출력하고 있습니다. 전자 매칭 오류 및 나는 왜 확신 할 수 없다. 어떤 도움이라도 대단히 감사합니다!

답변

3

아래 코드가 작동합니다. 사람들이 무슨 일이 일어나고 있는지 더 잘 이해할 수 있도록 유형 오류를 게시하면 도움이됩니다. 코드에 몇 가지 문제가 있습니다.

하나, 장르를 필터링하려고합니다. 장르는 bool이 아니라 문자열입니다. 문자열을 비교하려면 (==)를 사용해야합니다.

두 번째로, getGenres는 정의되어 있지 않지만 아티스트를 취하고 모든 장르를 반환한다고 가정하면 아티스트에 매핑하면 코드에서 원하는대로 수행되지 않습니다. 그것은 단지 당신에게 예술가의 추가 된 상황없이 장르를 줄 것입니다.

장르가 현재 아티스트의 요소 인 경우 아티스트를 필터링하는 것으로 생각합니다.

데이터 선언을 사용하여 수동으로 접근 함수를 만들지 않고도 자동으로 접근 함수를 만들 수 있습니다.

data Artist = Artist { 
    getName :: String, 
    getGenres :: Genres 
} deriving (Show) 

type Name = String 
type Genres = [Genre] 
type Genre = String 

getFilteredArtists :: [Artist] -> Genre -> [Artist] 
getFilteredArtists xs genre = filter (\x -> genre `elem` getGenres x) xs 

artists = [ 
    Artist "Grimes" ["Electropop", "Dream Pop", "Synthpop"], 
    Artist "My Bloody Valentine" ["Shoegaze", "Noise Pop", "Post Punk"], 
    Artist "David Bowie" ["Art Rock", "Pop Rock", "Glam Rock", "New Wave"] 
    ] 

main = print $ getFilteredArtists artists "Art Rock" 

상기 코드가 출력 :

[Artist {getName = "David Bowie", getGenres = ["Art Rock","Pop Rock","Glam Rock","New Wave"]}] 
3
genre :: Genre 
filter :: (a -> Bool) -> [a] -> [a] 
filter genre :: ??? 

대신에, 당신이 필요한 것은

getFilteredArtists xs genre = filter hasGenre xs where 
    hasGenre :: Artist -> Bool 

같은 술어는 어떻게 hasGenre를 작성하는 것입니다? 글쎄, 당신은 이미 getGenres 기능을 가지고, 표준 라이브러리는

elem :: Eq a => a -> [a] -> Bool 

기능을 가지고 있습니다. genresgenre이 포함 된 경우 genre `elem` genres == True, 그렇지 않은 경우 False입니다.