给定一个String类型,应返回Strings 例如。给定字符串“Second”应返回 - > “第一”,“第三” 这就是这个字符串之前的内容以及之后的内容。 (在某种意义上的对称关系)
这是我到目前为止所尝试的内容。
between :: String -> (String, String)
between "Second" = (“First”,"Third")
between "Third" = (“Second”,"Fourth")
between "Fourth" = (“Third”, "Fifth")
我试过的另一个
data Positions = First | Second | Third | Fourth | Fifth |
between :: Positions -> (String,String)
between Second = (“First”,"Third")
between Third = (“Second”,"Fourth")
between Fourth = (“Third”, "Fifth")
收到不同类型的错误,例如。未定义的变量 ”?” ,不正确终止的字符串和方程式给出了不同的元素。
如何解决这个问题以使其正常运行,没有任何错误?
答案 0 :(得分:1)
此代码中有两个语法错误。首先,您在|
类型的末尾有一个额外的Positions
。我喜欢以不同的方式编写ADT,以便在我搞砸之时更容易看到:
data Positions
= First
| Second
| Third
| Fourth
| Fifth
另一个错误是你似乎已经将一些非ascii引号字符复制/粘贴到每个第一个元组元素的源代码中,并且很容易修复:
between :: Positions -> (String, String)
between Second = ("First", "Third")
between Third = ("Second", "Fourth")
between Fourth = ("Third", "Fifth")
但是,我还要指出,在您的类型上使用deriving
子句可以更轻松地完成此操作:
data Positions
= First
| Second
| Third
| Fourth
| Fifth
deriving (Eq, Enum, Bounded)
between :: Positions -> Maybe (Positions, Positions)
between p =
if p == minBound || p == maxBound
then Nothing
else Just (pred p, succ p)
这使用Maybe
来使函数更安全,如果您调用between First
,它不会导致程序崩溃。如果您真的想要字符串,则可以derive (Eq, Enum, Bounded, Show)
使用Just (show $ pred p, show $ succ p)
答案 1 :(得分:0)
尊重您在问题开头提出的签名(String - >(String,String)),它看起来像这样:
between :: String -> (String, String)
between x = case x of
"Second" -> ("First","Third")
"Third" -> ("Second","Fourth")
"Fourth" -> ("Third","Fifth")