繁体   English   中英

将字符串转换为元组 Haskell

[英]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

请注意与原始版本的其他一些差异。

  1. 使用readMaybe代替read readMayberead的一个特殊版本,它返回Maybe a类型的值。 由于我们已经在Maybe上下文中工作,因此最好使用无解析返回Nothing而不是抛出错误。

  2. - 1行。 elemIndex已经具有您想要的行为,即A将返回0等。

  3. 模式匹配而不是headtail 这使您可以考虑字符串为空的情况。

  4. 额外定义以匹配空列表并返回Nothing 使用Maybe类型的优点是您可以返回错误值而不是获取运行时错误。 为了利用这一点,我们必须确保处理所有情况。

暂无
暂无

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

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