gpt4 book ai didi

Haskell 字符串到可能列表

转载 作者:行者123 更新时间:2023-12-01 10:35:23 25 4
gpt4 key购买 nike

readSquareTransition :: String -> Maybe [SquareTurn]
readSquareTransition [] = Just []
readSquareTransition (x:xs) = case x of
'L' -> Just (L : readSquareTransition xs)
'R' -> Just (R : readSquareTransition xs)
_ -> Nothing

我只想得到 [L,L,R,R]。但看起来我失败了:(这是错误信息!

src/StudentSources/LangtonsAnt.hs:231:24:
Couldn't match expected type ‘[SquareTurn]’
with actual type ‘Maybe [SquareTurn]’
In the second argument of ‘(:)’, namely ‘readSquareTransition xs’
In the first argument of ‘Just’, namely
‘(L : readSquareTransition xs)’

src/StudentSources/LangtonsAnt.hs:232:24:
Couldn't match expected type ‘[SquareTurn]’
with actual type ‘Maybe [SquareTurn]’
In the second argument of ‘(:)’, namely ‘readSquareTransition xs’
In the first argument of ‘Just’, namely
‘(R : readSquareTransition xs)’

最佳答案

这样做的模块化方法是首先定义 readSquareTurn,它定义如何将 Char 转换为单个 SquareTurn(使用失败的可能性):

readSquareTurn :: Char -> Maybe SquareTurn
readSquareTurn x = case x of
'L' -> Just L
'R' -> Just R
_ -> Nothing

然后使用 mapM::(a -> Maybe b) -> [a] -> Maybe [b] 来处理整个 String ,如下所示:

readSquareTransition :: String -> Maybe [SquareTurn]
readSquareTransition = mapM readSquareTurn

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

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