2012-11-22 2 views
1

데이터 유형 목록이 있고 첫 번째 값과 일치하는 데이터 유형이 있으면 찾고자합니다. 존재하지 않으면 기본값을 반환하고 싶습니다.haskell의 첫 번째 값을 비교하여 목록에서 데이터 유형을 찾습니다.

data MyType = MyType String Int 
findOrMake :: [MyType] -> String -> Int 
findOrMake list x = do i <- -- find index 
         -- if i is a value, return the x[i] 
         -- if i is not a value, return (MyType x 0) 

은 내가 fmapfind를 사용해야 직관을 가지고 있지만 나도 전에 사용 적이 없다.

답변

4

간단한 재귀 솔루션은 어떻습니까?

data MyType = MyType String Int 

findOrMake :: [MyType] -> String -> Int 
findOrMake [] s = 42 
findOrMake ((MyType mstr mint):ms) s = if mstr == s then mint else findOrMake ms s 
4

항목이 발견되지 않을 때 기본을 제공하기 위해, 당신은 fromMaybe 사용할 수 있습니다

fromMaybe defaultValue $ find predicate list 
: find과 결합

fromMaybe :: a -> Maybe a -> a 

를, 그것의 모양은

관련 문제