Passing a generic function as parameter

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












Ran into this idea and I'm curious if it's possible.



I'm trying to make a single function that can test ALL of my sorting algorithms dynamically. I want to be able to pass the sorting function as a parameter and the algorithm will use the sorting function with it's own dynamic parameters. This is an example of what I'm trying to do:



class manyFunctions
int mergeSort(int myArray)
...work here;
return sortedArray;


int otherSort(int myArray)
...work here;
return sortedArray;



class mainClass{
public static void main(StringArgs)
test(manyFunctions.mergeSort);
test(manyFunctions.otherSort);



boolean test(function someSortFunction)
int n; // number of trials
for (int i=0; i<=n ; i++)
int A = generateArray() // another function I made
if (isSorted(someSortFunction(A)) = false)
return false;


return true;



I can't figure out how to do this with the little bit I know about lambda expressions and function pointers. If it's possible, this technique would come in handy.







share|improve this question



























    up vote
    2
    down vote

    favorite












    Ran into this idea and I'm curious if it's possible.



    I'm trying to make a single function that can test ALL of my sorting algorithms dynamically. I want to be able to pass the sorting function as a parameter and the algorithm will use the sorting function with it's own dynamic parameters. This is an example of what I'm trying to do:



    class manyFunctions
    int mergeSort(int myArray)
    ...work here;
    return sortedArray;


    int otherSort(int myArray)
    ...work here;
    return sortedArray;



    class mainClass{
    public static void main(StringArgs)
    test(manyFunctions.mergeSort);
    test(manyFunctions.otherSort);



    boolean test(function someSortFunction)
    int n; // number of trials
    for (int i=0; i<=n ; i++)
    int A = generateArray() // another function I made
    if (isSorted(someSortFunction(A)) = false)
    return false;


    return true;



    I can't figure out how to do this with the little bit I know about lambda expressions and function pointers. If it's possible, this technique would come in handy.







    share|improve this question























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      Ran into this idea and I'm curious if it's possible.



      I'm trying to make a single function that can test ALL of my sorting algorithms dynamically. I want to be able to pass the sorting function as a parameter and the algorithm will use the sorting function with it's own dynamic parameters. This is an example of what I'm trying to do:



      class manyFunctions
      int mergeSort(int myArray)
      ...work here;
      return sortedArray;


      int otherSort(int myArray)
      ...work here;
      return sortedArray;



      class mainClass{
      public static void main(StringArgs)
      test(manyFunctions.mergeSort);
      test(manyFunctions.otherSort);



      boolean test(function someSortFunction)
      int n; // number of trials
      for (int i=0; i<=n ; i++)
      int A = generateArray() // another function I made
      if (isSorted(someSortFunction(A)) = false)
      return false;


      return true;



      I can't figure out how to do this with the little bit I know about lambda expressions and function pointers. If it's possible, this technique would come in handy.







      share|improve this question













      Ran into this idea and I'm curious if it's possible.



      I'm trying to make a single function that can test ALL of my sorting algorithms dynamically. I want to be able to pass the sorting function as a parameter and the algorithm will use the sorting function with it's own dynamic parameters. This is an example of what I'm trying to do:



      class manyFunctions
      int mergeSort(int myArray)
      ...work here;
      return sortedArray;


      int otherSort(int myArray)
      ...work here;
      return sortedArray;



      class mainClass{
      public static void main(StringArgs)
      test(manyFunctions.mergeSort);
      test(manyFunctions.otherSort);



      boolean test(function someSortFunction)
      int n; // number of trials
      for (int i=0; i<=n ; i++)
      int A = generateArray() // another function I made
      if (isSorted(someSortFunction(A)) = false)
      return false;


      return true;



      I can't figure out how to do this with the little bit I know about lambda expressions and function pointers. If it's possible, this technique would come in handy.









      share|improve this question












      share|improve this question




      share|improve this question








      edited Feb 7 at 10:08









      Zoe

      20519




      20519









      asked Feb 7 at 7:13









      HippoMano

      1314




      1314




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          Note: This answer is based on Java 8 and newer. This does not apply to Java 7, as Java 7 does not support Lambda



          For starters, your test function is wrong in multiple places:



          boolean test(function someSortFunction)//This is not how you pass functions
          int n; //this has to be initialized
          for (int i=0; i<=n ; i++) //Depending on how n is used, you may have to use < instead of <=
          int A = generateArray()//Missing semi-colon
          if (isSorted(someSortFunction(A)) = false) //Comparing is done with ==, not =
          return false;


          return true;



          In order to pass a function, you can either use Consumer<Void>, Supplier<Void>, Predicate<Void> or Function<Void, Void> (don't use Void as the type if you have return values)



          Supplier defines return type, Consumer defines input type, and function both. Meaning:



          • Use Predicate when you have a boolean return type with arguments

          • Use Supplier when you have a return type

          • Use Consumer when you have an argument

          • Use Function when you have both an argument and a return value

          Since you have both arguments and return types, use Function. The first argument you give it is the argument it receives, and the second is the return type. For an instance, in your case, this would be:



          boolean test(Function<int, int> someFunction) 


          Using Function requires calling apply to execute the method:



          int res = someFunction.apply(input);


          Before I move on, I'd like to take a second to mention naming conventions. In Java, class names always start with an upper case letter. Instances and functions start with a lower case letter. So your classes would be:



          public class ManyFunctions ...
          public class MainClass ...


          Passing methods are not done using someClass.someFunction. In your case, since you are not using static methods, you need to create an instance:



          ManyFunctions functions = new ManyFunctions();


          now, you pass the functions:



          test(functions::mergeSort);


          if you make the methods static, you can just skip the instance and use the class name directly:



          test(ManyFunctions::mergeSort);


          So your class would be:



          class MainClass
          public static void main(String args)
          ManyFunctions manyFunctions = new ManyFunctions();
          test(manyFunctions::mergeSort);//Notice the missing "()" and arguments
          test(manyFunctions::otherSort);



          boolean test(Function<int, int> someSortFunction)
          int n = 10;//THIS HAS TO BE INITIALIZED! Otherwise, it won't compile
          for (int i=0; i<=n ; i++)
          int A = generateArray();
          if (isSorted(someSortFunction.apply(A)) == false) //comparing is done with ==
          return false;


          return true;

          //Don't know if it was a copy-paste problem or not, but you had a missing bracket





          share|improve this answer























          • when the return type is boolean then the functional interface should be Predicate
            – Sharon Ben Asher
            Feb 7 at 9:36










          • I was looking at test() method itself
            – Sharon Ben Asher
            Feb 7 at 9:47










          • There are no methods being passed as arguments with a boolean return type in OP's code though (had to post a new comment, was too late to edit the previous one)
            – Zoe
            Feb 7 at 9:47











          • @SharonBenAsher test() is never passed anywhere. The only methods being passed have int return types
            – Zoe
            Feb 7 at 9:49






          • 1




            I apologize that, by trying to simplify my question/code, I made some distracting mistakes. The meat of the question is there though and your answer is really helpful and interesting! Thank you!
            – HippoMano
            Feb 7 at 19:39











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f186972%2fpassing-a-generic-function-as-parameter%23new-answer', 'question_page');

          );

          Post as a guest






























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          3
          down vote



          accepted










          Note: This answer is based on Java 8 and newer. This does not apply to Java 7, as Java 7 does not support Lambda



          For starters, your test function is wrong in multiple places:



          boolean test(function someSortFunction)//This is not how you pass functions
          int n; //this has to be initialized
          for (int i=0; i<=n ; i++) //Depending on how n is used, you may have to use < instead of <=
          int A = generateArray()//Missing semi-colon
          if (isSorted(someSortFunction(A)) = false) //Comparing is done with ==, not =
          return false;


          return true;



          In order to pass a function, you can either use Consumer<Void>, Supplier<Void>, Predicate<Void> or Function<Void, Void> (don't use Void as the type if you have return values)



          Supplier defines return type, Consumer defines input type, and function both. Meaning:



          • Use Predicate when you have a boolean return type with arguments

          • Use Supplier when you have a return type

          • Use Consumer when you have an argument

          • Use Function when you have both an argument and a return value

          Since you have both arguments and return types, use Function. The first argument you give it is the argument it receives, and the second is the return type. For an instance, in your case, this would be:



          boolean test(Function<int, int> someFunction) 


          Using Function requires calling apply to execute the method:



          int res = someFunction.apply(input);


          Before I move on, I'd like to take a second to mention naming conventions. In Java, class names always start with an upper case letter. Instances and functions start with a lower case letter. So your classes would be:



          public class ManyFunctions ...
          public class MainClass ...


          Passing methods are not done using someClass.someFunction. In your case, since you are not using static methods, you need to create an instance:



          ManyFunctions functions = new ManyFunctions();


          now, you pass the functions:



          test(functions::mergeSort);


          if you make the methods static, you can just skip the instance and use the class name directly:



          test(ManyFunctions::mergeSort);


          So your class would be:



          class MainClass
          public static void main(String args)
          ManyFunctions manyFunctions = new ManyFunctions();
          test(manyFunctions::mergeSort);//Notice the missing "()" and arguments
          test(manyFunctions::otherSort);



          boolean test(Function<int, int> someSortFunction)
          int n = 10;//THIS HAS TO BE INITIALIZED! Otherwise, it won't compile
          for (int i=0; i<=n ; i++)
          int A = generateArray();
          if (isSorted(someSortFunction.apply(A)) == false) //comparing is done with ==
          return false;


          return true;

          //Don't know if it was a copy-paste problem or not, but you had a missing bracket





          share|improve this answer























          • when the return type is boolean then the functional interface should be Predicate
            – Sharon Ben Asher
            Feb 7 at 9:36










          • I was looking at test() method itself
            – Sharon Ben Asher
            Feb 7 at 9:47










          • There are no methods being passed as arguments with a boolean return type in OP's code though (had to post a new comment, was too late to edit the previous one)
            – Zoe
            Feb 7 at 9:47











          • @SharonBenAsher test() is never passed anywhere. The only methods being passed have int return types
            – Zoe
            Feb 7 at 9:49






          • 1




            I apologize that, by trying to simplify my question/code, I made some distracting mistakes. The meat of the question is there though and your answer is really helpful and interesting! Thank you!
            – HippoMano
            Feb 7 at 19:39















          up vote
          3
          down vote



          accepted










          Note: This answer is based on Java 8 and newer. This does not apply to Java 7, as Java 7 does not support Lambda



          For starters, your test function is wrong in multiple places:



          boolean test(function someSortFunction)//This is not how you pass functions
          int n; //this has to be initialized
          for (int i=0; i<=n ; i++) //Depending on how n is used, you may have to use < instead of <=
          int A = generateArray()//Missing semi-colon
          if (isSorted(someSortFunction(A)) = false) //Comparing is done with ==, not =
          return false;


          return true;



          In order to pass a function, you can either use Consumer<Void>, Supplier<Void>, Predicate<Void> or Function<Void, Void> (don't use Void as the type if you have return values)



          Supplier defines return type, Consumer defines input type, and function both. Meaning:



          • Use Predicate when you have a boolean return type with arguments

          • Use Supplier when you have a return type

          • Use Consumer when you have an argument

          • Use Function when you have both an argument and a return value

          Since you have both arguments and return types, use Function. The first argument you give it is the argument it receives, and the second is the return type. For an instance, in your case, this would be:



          boolean test(Function<int, int> someFunction) 


          Using Function requires calling apply to execute the method:



          int res = someFunction.apply(input);


          Before I move on, I'd like to take a second to mention naming conventions. In Java, class names always start with an upper case letter. Instances and functions start with a lower case letter. So your classes would be:



          public class ManyFunctions ...
          public class MainClass ...


          Passing methods are not done using someClass.someFunction. In your case, since you are not using static methods, you need to create an instance:



          ManyFunctions functions = new ManyFunctions();


          now, you pass the functions:



          test(functions::mergeSort);


          if you make the methods static, you can just skip the instance and use the class name directly:



          test(ManyFunctions::mergeSort);


          So your class would be:



          class MainClass
          public static void main(String args)
          ManyFunctions manyFunctions = new ManyFunctions();
          test(manyFunctions::mergeSort);//Notice the missing "()" and arguments
          test(manyFunctions::otherSort);



          boolean test(Function<int, int> someSortFunction)
          int n = 10;//THIS HAS TO BE INITIALIZED! Otherwise, it won't compile
          for (int i=0; i<=n ; i++)
          int A = generateArray();
          if (isSorted(someSortFunction.apply(A)) == false) //comparing is done with ==
          return false;


          return true;

          //Don't know if it was a copy-paste problem or not, but you had a missing bracket





          share|improve this answer























          • when the return type is boolean then the functional interface should be Predicate
            – Sharon Ben Asher
            Feb 7 at 9:36










          • I was looking at test() method itself
            – Sharon Ben Asher
            Feb 7 at 9:47










          • There are no methods being passed as arguments with a boolean return type in OP's code though (had to post a new comment, was too late to edit the previous one)
            – Zoe
            Feb 7 at 9:47











          • @SharonBenAsher test() is never passed anywhere. The only methods being passed have int return types
            – Zoe
            Feb 7 at 9:49






          • 1




            I apologize that, by trying to simplify my question/code, I made some distracting mistakes. The meat of the question is there though and your answer is really helpful and interesting! Thank you!
            – HippoMano
            Feb 7 at 19:39













          up vote
          3
          down vote



          accepted







          up vote
          3
          down vote



          accepted






          Note: This answer is based on Java 8 and newer. This does not apply to Java 7, as Java 7 does not support Lambda



          For starters, your test function is wrong in multiple places:



          boolean test(function someSortFunction)//This is not how you pass functions
          int n; //this has to be initialized
          for (int i=0; i<=n ; i++) //Depending on how n is used, you may have to use < instead of <=
          int A = generateArray()//Missing semi-colon
          if (isSorted(someSortFunction(A)) = false) //Comparing is done with ==, not =
          return false;


          return true;



          In order to pass a function, you can either use Consumer<Void>, Supplier<Void>, Predicate<Void> or Function<Void, Void> (don't use Void as the type if you have return values)



          Supplier defines return type, Consumer defines input type, and function both. Meaning:



          • Use Predicate when you have a boolean return type with arguments

          • Use Supplier when you have a return type

          • Use Consumer when you have an argument

          • Use Function when you have both an argument and a return value

          Since you have both arguments and return types, use Function. The first argument you give it is the argument it receives, and the second is the return type. For an instance, in your case, this would be:



          boolean test(Function<int, int> someFunction) 


          Using Function requires calling apply to execute the method:



          int res = someFunction.apply(input);


          Before I move on, I'd like to take a second to mention naming conventions. In Java, class names always start with an upper case letter. Instances and functions start with a lower case letter. So your classes would be:



          public class ManyFunctions ...
          public class MainClass ...


          Passing methods are not done using someClass.someFunction. In your case, since you are not using static methods, you need to create an instance:



          ManyFunctions functions = new ManyFunctions();


          now, you pass the functions:



          test(functions::mergeSort);


          if you make the methods static, you can just skip the instance and use the class name directly:



          test(ManyFunctions::mergeSort);


          So your class would be:



          class MainClass
          public static void main(String args)
          ManyFunctions manyFunctions = new ManyFunctions();
          test(manyFunctions::mergeSort);//Notice the missing "()" and arguments
          test(manyFunctions::otherSort);



          boolean test(Function<int, int> someSortFunction)
          int n = 10;//THIS HAS TO BE INITIALIZED! Otherwise, it won't compile
          for (int i=0; i<=n ; i++)
          int A = generateArray();
          if (isSorted(someSortFunction.apply(A)) == false) //comparing is done with ==
          return false;


          return true;

          //Don't know if it was a copy-paste problem or not, but you had a missing bracket





          share|improve this answer















          Note: This answer is based on Java 8 and newer. This does not apply to Java 7, as Java 7 does not support Lambda



          For starters, your test function is wrong in multiple places:



          boolean test(function someSortFunction)//This is not how you pass functions
          int n; //this has to be initialized
          for (int i=0; i<=n ; i++) //Depending on how n is used, you may have to use < instead of <=
          int A = generateArray()//Missing semi-colon
          if (isSorted(someSortFunction(A)) = false) //Comparing is done with ==, not =
          return false;


          return true;



          In order to pass a function, you can either use Consumer<Void>, Supplier<Void>, Predicate<Void> or Function<Void, Void> (don't use Void as the type if you have return values)



          Supplier defines return type, Consumer defines input type, and function both. Meaning:



          • Use Predicate when you have a boolean return type with arguments

          • Use Supplier when you have a return type

          • Use Consumer when you have an argument

          • Use Function when you have both an argument and a return value

          Since you have both arguments and return types, use Function. The first argument you give it is the argument it receives, and the second is the return type. For an instance, in your case, this would be:



          boolean test(Function<int, int> someFunction) 


          Using Function requires calling apply to execute the method:



          int res = someFunction.apply(input);


          Before I move on, I'd like to take a second to mention naming conventions. In Java, class names always start with an upper case letter. Instances and functions start with a lower case letter. So your classes would be:



          public class ManyFunctions ...
          public class MainClass ...


          Passing methods are not done using someClass.someFunction. In your case, since you are not using static methods, you need to create an instance:



          ManyFunctions functions = new ManyFunctions();


          now, you pass the functions:



          test(functions::mergeSort);


          if you make the methods static, you can just skip the instance and use the class name directly:



          test(ManyFunctions::mergeSort);


          So your class would be:



          class MainClass
          public static void main(String args)
          ManyFunctions manyFunctions = new ManyFunctions();
          test(manyFunctions::mergeSort);//Notice the missing "()" and arguments
          test(manyFunctions::otherSort);



          boolean test(Function<int, int> someSortFunction)
          int n = 10;//THIS HAS TO BE INITIALIZED! Otherwise, it won't compile
          for (int i=0; i<=n ; i++)
          int A = generateArray();
          if (isSorted(someSortFunction.apply(A)) == false) //comparing is done with ==
          return false;


          return true;

          //Don't know if it was a copy-paste problem or not, but you had a missing bracket






          share|improve this answer















          share|improve this answer



          share|improve this answer








          edited Apr 22 at 8:27









          Billal BEGUERADJ

          1




          1











          answered Feb 7 at 8:17









          Zoe

          20519




          20519











          • when the return type is boolean then the functional interface should be Predicate
            – Sharon Ben Asher
            Feb 7 at 9:36










          • I was looking at test() method itself
            – Sharon Ben Asher
            Feb 7 at 9:47










          • There are no methods being passed as arguments with a boolean return type in OP's code though (had to post a new comment, was too late to edit the previous one)
            – Zoe
            Feb 7 at 9:47











          • @SharonBenAsher test() is never passed anywhere. The only methods being passed have int return types
            – Zoe
            Feb 7 at 9:49






          • 1




            I apologize that, by trying to simplify my question/code, I made some distracting mistakes. The meat of the question is there though and your answer is really helpful and interesting! Thank you!
            – HippoMano
            Feb 7 at 19:39

















          • when the return type is boolean then the functional interface should be Predicate
            – Sharon Ben Asher
            Feb 7 at 9:36










          • I was looking at test() method itself
            – Sharon Ben Asher
            Feb 7 at 9:47










          • There are no methods being passed as arguments with a boolean return type in OP's code though (had to post a new comment, was too late to edit the previous one)
            – Zoe
            Feb 7 at 9:47











          • @SharonBenAsher test() is never passed anywhere. The only methods being passed have int return types
            – Zoe
            Feb 7 at 9:49






          • 1




            I apologize that, by trying to simplify my question/code, I made some distracting mistakes. The meat of the question is there though and your answer is really helpful and interesting! Thank you!
            – HippoMano
            Feb 7 at 19:39
















          when the return type is boolean then the functional interface should be Predicate
          – Sharon Ben Asher
          Feb 7 at 9:36




          when the return type is boolean then the functional interface should be Predicate
          – Sharon Ben Asher
          Feb 7 at 9:36












          I was looking at test() method itself
          – Sharon Ben Asher
          Feb 7 at 9:47




          I was looking at test() method itself
          – Sharon Ben Asher
          Feb 7 at 9:47












          There are no methods being passed as arguments with a boolean return type in OP's code though (had to post a new comment, was too late to edit the previous one)
          – Zoe
          Feb 7 at 9:47





          There are no methods being passed as arguments with a boolean return type in OP's code though (had to post a new comment, was too late to edit the previous one)
          – Zoe
          Feb 7 at 9:47













          @SharonBenAsher test() is never passed anywhere. The only methods being passed have int return types
          – Zoe
          Feb 7 at 9:49




          @SharonBenAsher test() is never passed anywhere. The only methods being passed have int return types
          – Zoe
          Feb 7 at 9:49




          1




          1




          I apologize that, by trying to simplify my question/code, I made some distracting mistakes. The meat of the question is there though and your answer is really helpful and interesting! Thank you!
          – HippoMano
          Feb 7 at 19:39





          I apologize that, by trying to simplify my question/code, I made some distracting mistakes. The meat of the question is there though and your answer is really helpful and interesting! Thank you!
          – HippoMano
          Feb 7 at 19:39













           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f186972%2fpassing-a-generic-function-as-parameter%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Greedy Best First Search implementation in Rust

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          C++11 CLH Lock Implementation