How do you return two values from a single method?

后端 未结 22 798
谎友^
谎友^ 2020-12-11 00:58

When your in a situation where you need to return two things in a single method, what is the best approach?

I understand the philosophy that a method should do one t

22条回答
  •  旧巷少年郎
    2020-12-11 01:48

    Haskell also allows multiple return values using built in tuples:

    sumAndDifference        :: Int -> Int -> (Int, Int)
    sumAndDifference x y    = (x + y, x - y)
    
    > let (s, d) = sumAndDifference 3 5 in s * d
    -16
    

    Being a pure language, options 1 and 2 are not allowed.

    Even using a state monad, the return value contains (at least conceptually) a bag of all relevant state, including any changes the function just made. It's just a fancy convention for passing that state through a sequence of operations.

提交回复
热议问题