繁体   English   中英

字符串到Int列表

[英]String to List of 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

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

问题出在这一行:

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

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

为了解决这个问题,您可以使用fmap<$>将函数应用于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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM