将字符串转换为我自己的数据类型,反之亦然

Converting Strings into my own data type and vice versa

我正在做一个 Haskell 学校作业,要求我将字符串转换为自定义数据类型:Position,它应该只包含一个字符 (A-H) 和一个 Int(1 -4).(即A1, B3, H4)

函数的用法如下: toPosition 只给出由字符串命名的位置,如果字符串不是有效的位置名称,则返回 Nothing。

这是我的尝试: 我将数据类型定义为:

data Position = Pos Char Int

然后我对 toPosition 的尝试:

toPosition :: String -> Maybe Position
toPosition [] = Nothing
toPosition (x:xs) 
           | len(xs) == 1 = Loc x xs
           | otherwise = Nothing

GHCi returning

 'Not in scope: type constructor or class ‘Pos’'

有什么想法可以解决此问题并验证输入,以便在输入合法时它只会 return 一个字符串 'Position'?

---更新一号----

我将我的代码更新为以下内容:

type Position = Pos Char Int

toPosition :: String -> Maybe Position
toPosition string = case string of
  first : second : rest ->
    if isValidChar first
      then if isValidInt second
        then if null rest
          then Just (Pos first (read second :: Int))
          else Nothing -- more than two characters
        else Nothing -- invalid second character
      else Nothing -- invalid first character

isValidChar :: Char -> Bool
isValidChar x
    |x == "A" || "B" || "C" || "D" || "E" || "F" || "G" || "H" = True
    |otherwise = False

isValidInt :: Char -> Bool
isValidInt x
    |x == 1 || 2 || 3 || 4 = True
    |otherwise = False

它仍然给我错误:

Not in scope: type constructor or class ‘Pos’

所以我想知道如何表示我自定义的数据类型,这样我就不会再收到任何错误?

由于这是作业,我不会提供完整的解决方案,但希望我能提供足够的帮助让你摆脱困境。

您可以使用模式匹配从字符串中获取第一个和第二个字符。然后您可以使用普通函数来确定这些字符是否有效。假设它们是,您可以将 Position 值构建为 return.

data Position = Pos Char Int

toPosition :: String -> Maybe Position
toPosition string = case string of
  first : second : rest ->
    if isValidChar first
      then if isValidInt second
        then if null rest
          then Just (Pos first (charToInt second))
          else Nothing -- more than two characters
        else Nothing -- invalid second character
      else Nothing -- invalid first character
  anythingElse -> Nothing -- fewer than two characters

isValidChar :: Char -> Bool
isValidChar = undefined

isValidInt :: Char -> Bool
isValidInt = undefined

charToInt :: Char -> Int
charToInt = undefined