[英]Haskell: test if list length < 4
I have the following haskell function that returns Nothing
if the String
is shorter than 4 characters: 我有以下haskell函数,如果
String
小于4个字符,则返回Nothing
:
stringToMove :: String -> Maybe Move
stringToMove [] = Nothing
stringToMove [a] = Nothing
stringToMove [a, b] = Nothing
stringToMove [a, b, c] = Nothing
stringToMove (l1:n1:l2:n2:rest) = Just (stringToCoords l1 n1, stringToCoords l2 n2)
I could test on length string
, but as far as I read, this is not the haskell way of writing this, since if String
is long, all of it will be evaluated. 我可以对
length string
测试,但据我所读,这不是编写此代码的haskell方法,因为如果String
很长,则将对所有String
进行求值。
Is there an elegant way of writing this without having to repeat Nothing
in each line? 是否有一种优雅的书写方式,而不必在每行中重复
Nothing
?
stringToMove :: String -> Maybe Move
stringToMove (l1:n1:l2:n2:rest) = Just (stringToCoords l1 n1, stringToCoords l2 n2)
stringToMove _ = Nothing
I just feel like chiming in, if you have a lot of checks like this and you want to return a Maybe
, you can use do
notation: 我只是想插话,如果您有很多这样的检查并且想返回
Maybe
,则可以使用do
表示法:
stringToMove :: String -> Maybe Move
stringToMove s = do
l1:n1:l2:n2:_ <- return s
return (stringToCoords l1 n1, stringToCoords l2 n2)
You can do failable bindings as many times as you like, and if any of them fails, the function will return Nothing
. 您可以根据需要执行多次失败的绑定,如果绑定失败,该函数将返回
Nothing
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.