String Haskell:返回在&;之前的字符串;在给定字符串之后
给定类型字符串,则应返回字符串 给定字符串“Second”应该返回-->“First”,“Third” 这就是这个字符串前面和后面的内容。(某种意义上的对称关系) 以下是我到目前为止所做的尝试String Haskell:返回在&;之前的字符串;在给定字符串之后,string,haskell,String,Haskell,给定类型字符串,则应返回字符串 给定字符串“Second”应该返回-->“First”,“Third” 这就是这个字符串前面和后面的内容。(某种意义上的对称关系) 以下是我到目前为止所做的尝试 between :: String -> (String, String) between "Second" = (“First”,"Third") between "Third" = (“Second”,"Fourth") between "Fourth" = (“Third”, "Fifth"
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")
接收到不同类型的错误,例如未定义的变量“?”、不正确终止的字符串和公式给出不同的算术
您将如何修复此问题,使其能够正常运行,而不会出现任何错误?此代码中有两个语法错误。首先,在
位置
类型的末尾有一个额外的|
。我喜欢以不同的方式编写我的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")
但是,我还要指出,在您的类型上使用派生
子句可以更轻松地完成这项工作:
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
使函数更安全,如果在第一次调用之间调用,它不会使程序崩溃。如果您真的想要字符串,您可以派生(Eq,Enum,Bounded,Show)
并使用仅仅(Show$pred p,Show$such p)
关于您在问题开始时提出的签名(String->(String,String)),它可以是这样的:
between :: String -> (String, String)
between x = case x of
"Second" -> ("First","Third")
"Third" -> ("Second","Fourth")
"Fourth" -> ("Third","Fifth")
特殊引号(“
和”
)是复制和粘贴问题,还是您在源文件中实际使用了这些引号?