我正在做一項 Haskell 學校作業,要求我將字串轉換為自定義資料型別:Position,它應該只包含一個 (AH) 字符和一個 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回傳
'Not in scope: type constructor or class ‘Pos’'
有什么想法可以解決這個問題并驗證輸入,以便它只在輸入是合法的“位置”時回傳一個字串?
---更新一號----
我將我的代碼更新為以下內容:
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’
所以我想知道如何表示我的自定義資料型別,這樣我就不會再出現錯誤了?
uj5u.com熱心網友回復:
由于這是家庭作業,我不會提供完整的解決方案,但希望我能提供足夠的幫助讓您擺脫困境。
您可以使用模式匹配從字串中獲取第一個和第二個字符。然后您可以使用普通函式來確定這些字符是否有效。假設它們是,您可以構建一個Position回傳值。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474047.html
標籤:哈斯克尔
