Haskell: Multiple Case Statements in Single Function

后端 未结 3 803
鱼传尺愫
鱼传尺愫 2021-02-15 10:06

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:27

    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)
    

提交回复
热议问题