[英]Converting String to Tuple Haskell
I'm trying to create a function for a board game that will read a position on the board as a string and convert to a coordinate that can be used in the program eg "D4 => (3,3), "F2" => (5,1)"
.我正在尝试为棋盘游戏创建 function,它将读取棋盘上的 position 作为字符串并转换为可在程序中使用的坐标,例如
"D4 => (3,3), "F2" => (5,1)"
。
So far I have this:到目前为止,我有这个:
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)
I'm still learning about the use of Maybe
in Haskell and am encountering the error:我仍在学习有关在 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)
Would appreciate your help on where I might be going wrong.感谢您对我可能出错的地方的帮助。 Thanks!
谢谢!
The problem you're facing is that elemIndex
returns a Maybe Int
.您面临的问题是
elemIndex
返回Maybe Int
。 Since you're also trying to return a Maybe
type, the best way to work with this is using a do
block to perform operations inside the Maybe
monad.由于您还尝试返回
Maybe
类型,因此使用它的最佳方法是使用do
块在Maybe
monad 中执行操作。 This lets you use Maybe
values as if they were normal values as long as your output will get wrapped back up in a Maybe
.这使您可以像使用正常值一样使用
Maybe
值,只要您的 output 将被包装在Maybe
中。 (If you need more information about how monads work, there are plenty of good answers here explaining it, and lots of other great posts across the internet.) (如果您需要有关 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
Note a couple other differences from your original.请注意与原始版本的其他一些差异。
The use of readMaybe
instead of read
.使用
readMaybe
代替read
。 readMaybe
is a special version of read
that returns a value of type Maybe a
. readMaybe
是read
的一个特殊版本,它返回Maybe a
类型的值。 Since we're already working in a Maybe
context, it's better to have a no-parse return Nothing
than throw an error.由于我们已经在
Maybe
上下文中工作,因此最好使用无解析返回Nothing
而不是抛出错误。
No - 1
on the row.否
- 1
行。 elemIndex
already has the behavior you want, ie A
will return 0
, etc. elemIndex
已经具有您想要的行为,即A
将返回0
等。
Pattern match instead of head
and tail
.模式匹配而不是
head
和tail
。 This lets you account for the case where the string is empty.这使您可以考虑字符串为空的情况。
Extra definition to match empty list and return Nothing
.额外定义以匹配空列表并返回
Nothing
。 The advantage of using a Maybe
type is that you can return a value for errors instead of getting a Runtime error.使用
Maybe
类型的优点是您可以返回错误值而不是获取运行时错误。 In order to make use of that, we have to make sure we handle all of the cases.为了利用这一点,我们必须确保处理所有情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.