Haskell: Multiple Case Statements in Single Function

后端 未结 3 831
故里飘歌
故里飘歌 2021-02-15 09:58

I want to include more than one case statement in a Haskell function (see below for an example of a hypothetical function).

However, it is not legal Haskell. What is a b

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-15 10:38

    In general, it looks like what you want is guards. However, as already mentioned, your function is not a single expression. Assuming that you want to return a tuple of strings, it can be written like this using guards (and some added fun from Arrows):

    import Control.Arrow
    
    testx x | x < 0      = "Less then zero."
            | otherwise  = "Greater then or equal to zero."
    
    testy y | y == "foo" = "The name is foo."
            | otherwise  = "The name is not foo."
    
    tester = curry (testx *** testy)
    

    You could also drop the Control.Arrow bit all together and write:

    tester x y = (testx x, testy y)
    

提交回复
热议问题