简体   繁体   English

Haskell:测试列表长度是否小于4

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM