Home > Net >  Haskell - Join two functions with the same input
Haskell - Join two functions with the same input

Time:10-25

I have 2 different very simple functions with the same input-output structure (Both return a count(*) when avg of 3 notes is >= 4 (function1) and the other a count(*) when avg of 3 notes is < 4 (function2)), They both work properly in separate but now i need to join both into just one function with 2 outputs, I now maybe is a very easy question but i am only getting started with Haskell:

function1::[(String, Int,Int,Int)]->Int
function1 ((name,note1,note2,note3):xs) = 
    if (note1 note2 note3) `div` 3 >=4 then length xs else length xs

function2::[(String, Int,Int,Int)]->Int
function2 ((name,note1,note2,note3):xs) = 
    if (note1 note2 note3) `div` 3 <4 then length xs else length xs

Thanks!

CodePudding user response:

You can use &&& from Control.Arrow.

combineFunctions f1 f2 = f1 &&& f2

Then use it like this :

combinedFunc = combineFunctions function1 function2
(res1,res2) = combinedFunc  sharedArg

CodePudding user response:

You already use tuples (name,note1,note2,note3) in your input data, so you must be familiar with the concept.

The simplest way to produce two outputs simultaneously is to put the two into one tuple:

combinedFunction f1 f2 input = (out1, out2)
   where
   out1 = f1 input
   out2 = f2 input

It so happens that this can be written shorter as combinedFunction f1 f2 = f1 &&& f2 and even combinedFunction = (&&&), but that's less important for now.

A more interesting way to produce two outputs simultaneously is to redefine what it means to produce an output:

combinedFunWith k f1 f2 input = k out1 out2
   where
   out1 = f1 input
   out2 = f2 input

Here instead of just returning them in a tuple, we pass them as arguments to some other user-specified function k. Let it decide what to do with the two outputs!

As can also be readily seen, our first version can be expressed with the second, as combinedFunction = combinedFunWith (,), so the second one seems to be more general ((,) is just a shorter way of writing a function foo x y = (x,y), without giving it a name).

  • Related