字符串到Int列表

ads*_*345 3 string int haskell

我想将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
Run Code Online (Sandbox Code Playgroud)

我试过了,但它显示了一个错误列表

text2digits :: String -> Maybe [Int]
text2digits s = case s of
    []          -> Just []
        x:xs        
        |isDigit x      -> Just digitToInt x :text2digits (filter (/= ' ') xs)
        |otherwise      -> Nothing
Run Code Online (Sandbox Code Playgroud)

Igo*_*dov 5

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

问题出在这一行:

digitToInt x :text2digits (filter (/= ' ') xs)
Run Code Online (Sandbox Code Playgroud)

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"
Run Code Online (Sandbox Code Playgroud)

或者你可以使用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"
Run Code Online (Sandbox Code Playgroud)