gpt4 book ai didi

字符串到 Int 列表

转载 作者:行者123 更新时间:2023-12-02 10:54:39 25 4
gpt4 key购买 nike

我想将 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<$>将函数应用于仿函数内的结构 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"

关于字符串到 Int 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46357690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com