字符串到Int列表

时间:2017-09-22 05:51:15

标签: string haskell int

我想将Maybe [int]纳入此内容。

代码应该采用字符串并过滤掉空格,将其转换为整数列表,如果它们是字母则返回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

1 个答案:

答案 0 :(得分:5)

您为text2digits :: String -> Maybe [Int]指定的代码有什么问题?

问题出在这一行:

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

text2digits返回Maybe [Int]类型的值,但(:)期望它为[Int]

为了解决此问题,您可以使用fmap<$>将函数应用于仿函数Maybe内的结构:

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来重构函数:

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"