[英]Converting String to Tuple Haskell
我正在尝试为棋盘游戏创建 function,它将读取棋盘上的 position 作为字符串并转换为可在程序中使用的坐标,例如"D4 => (3,3), "F2" => (5,1)"
。
到目前为止,我有这个:
getCoord :: String -> Maybe(Int, Int)
getCoord s =
let alphas = "ABCDEFGH"
coord1 = head(s)
coord2 = tail(s)
in ((elemIndex coord1 alphas)-1, read(head coord2)-1)
我仍在学习有关在 Haskell 中使用Maybe
并遇到错误:
• Couldn't match expected type ‘Maybe (Int, Int)’
with actual type ‘(Maybe Int, Integer)’
• In the expression:
((elemIndex coord1 alphas) - 1, read (head coord2) - 1)
感谢您对我可能出错的地方的帮助。 谢谢!
您面临的问题是elemIndex
返回Maybe Int
。 由于您还尝试返回Maybe
类型,因此使用它的最佳方法是使用do
块在Maybe
monad 中执行操作。 这使您可以像使用正常值一样使用Maybe
值,只要您的 output 将被包装在Maybe
中。 (如果您需要有关 monad 如何工作的更多信息,这里有很多很好的答案来解释它,以及互联网上许多其他很棒的帖子。)
import Text.Read (readMaybe)
import Data.List (elemIndex)
getCoords :: String -> Maybe(Int, Int)
getCoords (coord1:coord2) = do
let alphas = "ABCDEFGH"
row <- elemIndex coord1 alphas
col <- readMaybe coord2
return (row, col - 1)
getCoords _ = Nothing
请注意与原始版本的其他一些差异。
使用readMaybe
代替read
。 readMaybe
是read
的一个特殊版本,它返回Maybe a
类型的值。 由于我们已经在Maybe
上下文中工作,因此最好使用无解析返回Nothing
而不是抛出错误。
否- 1
行。 elemIndex
已经具有您想要的行为,即A
将返回0
等。
模式匹配而不是head
和tail
。 这使您可以考虑字符串为空的情况。
额外定义以匹配空列表并返回Nothing
。 使用Maybe
类型的优点是您可以返回错误值而不是获取运行时错误。 为了利用这一点,我们必须确保处理所有情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.