2017-09-22 5 views
2

Maybe [int]를 여기에 포함시키고 싶습니다.Int of List of int of

코드는 문자열을 가져 와서 정수 목록으로 바꾸고 공백을 필터링하여 문자가 Nothing을 반환하면됩니다.

text2digits :: String -> [Int] 
text2digits s = case s of 
    []   -> [] 
    x:xs   
     |isDigit x  -> digitToInt x :text2digits (filter (/= ' ') xs) 
     |otherwise  -> undefined 

input "1233 5687" output: [1,2,3,3,5,6,8,7] 
input "a89"  required output : Nothing 
        current output: undefined 

나는이 시도하지만

text2digits :: String -> Maybe [Int] 
text2digits s = case s of 
    []   -> Just [] 
     x:xs   
     |isDigit x  -> Just digitToInt x :text2digits (filter (/= ' ') xs) 
     |otherwise  -> Nothing 
+0

현재 코드에 어떤 문제가 있는지 명시하십시오. 입력 및 예상 출력 예를 제공하십시오. –

+0

'otherwise'의 경우'Nothing'을 반환하십시오. 그러나 isDigit' case와'[]' case의 리턴 타입을'Maybe [Int] '로 변경해야합니다. 당신은'그냥'을 사용함으로써 그렇게 할 수 있습니다. –

+0

'Nothing'을리스트와 병합 할 수 없습니다 ... –

답변

5

당신이 text2digits :: String -> Maybe [Int]에 지정한 것으로, 코드에 어떤 문제가 오류의 목록을 보여줍니다? Maybe [Int] 유형의

digitToInt x :text2digits (filter (/= ' ') xs) 

text2digits 반환 값,하지만 (:)[Int]있을 것으로 기대 :

문제는이 라인에있다.

import Data.Char 

text2digits :: String -> Maybe [Int] 
text2digits s = case s of 
    [] -> Just [] 
    x:xs 
     |isDigit x  -> ((digitToInt x) :) <$> text2digits (filter (/= ' ') xs) 
     |otherwise  -> Nothing 

main = print $ text2digits "1233 5687" 

또는 아마 당신이 기능을 약간 리팩토링 traverse를 사용할 수 있습니다 :

를 해결하기 위해, 당신은 펑 Maybe 내부 구조에 함수를 적용 할 fmap 또는 <$>을 사용할 수 있습니다

import Data.Char 

text2digits :: String -> Maybe [Int] 
text2digits s = 
    traverse digitToMaybeInt $ filter (/= ' ') s 
    where 
    digitToMaybeInt x 
     | isDigit x = Just $ digitToInt x 
     | otherwise = Nothing 

main = print $ text2digits "89"