【发布时间】:2019-04-01 01:34:50
【问题描述】:
我有一个名为 pitch 的自定义数据结构,其中包含 2 个变量 note 和 octave。我需要将字符串转换为音高,因此我编写了一个函数,该函数将字符串作为输入,将 Maybe Pitch 作为返回值,因为可能存在一些无效输入。然后我自定义了我的显示功能,当我在 ghci 中测试它时,它显示“Just A2”(A2 是音高值)。这是我的代码:
data Pitch = Pitch { note :: Char, octave :: Int }deriving (Eq)
toPitch :: String -> Maybe Pitch
toPitch str
| strlen == 2 && (note >= 'A' && note <= 'G')
&& (octave >= 1 && octave <= 3) = Just (Pitch note octave)
| otherwise = Nothing
where
strlen = length str
note = head str
octave = digitToInt (str!!1)
toString :: Maybe Pitch -> String
toString (Just pitch) = [note pitch] ++ [(intToDigit (octave pitch))]
instance Show Pitch where
show pitch = toString (Just pitch)
下面是测试结果:
*Main> let pitch = toPitch "A2"
*Main> show pitch
"Just A2"
*Main>
有人可以告诉我如何在显示功能中删除它吗?非常感谢!
【问题讨论】:
-
如果那里有
Nothing呢? -
提示:使用
case语句。或者,编写一个模式匹配的新函数。 -
如果我们确定该变量中存在值,是否有任何方法可以删除 Maybe 包装器?在我的项目中,另一个将 [Pitch] 作为输入而不是 [Maybe Pitch] 的函数。
-
@AJFarmar 你为什么删除你的答案?这正是我看完问题后想写的答案。
-
@DanielWagner 我意识到主要问题是提问者是
show@Maybe Pitch,而不是他们写错了show。如果你真的认为它有用,我会恢复它。
标签: haskell