Swapping Variables by pattern matching?












0















Assume you have 2 Integer Variables a and b
How would you swap them only if a > b by using a match expression?
If a <= b do not swap the ints.



In an imperative language:



if (a > b){
int temp=a;
a=b;
b=temp;
}


Doing the same in ocaml seems surprisingly hard.



I tried



let swap a b = 
match a,b with
| a,b when a > b -> b,a
| a,b when a <= b -> a,b


I am trying to do this because in the following function call, I want to make sure that x is the bigger of the two variables.










share|improve this question





























    0















    Assume you have 2 Integer Variables a and b
    How would you swap them only if a > b by using a match expression?
    If a <= b do not swap the ints.



    In an imperative language:



    if (a > b){
    int temp=a;
    a=b;
    b=temp;
    }


    Doing the same in ocaml seems surprisingly hard.



    I tried



    let swap a b = 
    match a,b with
    | a,b when a > b -> b,a
    | a,b when a <= b -> a,b


    I am trying to do this because in the following function call, I want to make sure that x is the bigger of the two variables.










    share|improve this question



























      0












      0








      0








      Assume you have 2 Integer Variables a and b
      How would you swap them only if a > b by using a match expression?
      If a <= b do not swap the ints.



      In an imperative language:



      if (a > b){
      int temp=a;
      a=b;
      b=temp;
      }


      Doing the same in ocaml seems surprisingly hard.



      I tried



      let swap a b = 
      match a,b with
      | a,b when a > b -> b,a
      | a,b when a <= b -> a,b


      I am trying to do this because in the following function call, I want to make sure that x is the bigger of the two variables.










      share|improve this question
















      Assume you have 2 Integer Variables a and b
      How would you swap them only if a > b by using a match expression?
      If a <= b do not swap the ints.



      In an imperative language:



      if (a > b){
      int temp=a;
      a=b;
      b=temp;
      }


      Doing the same in ocaml seems surprisingly hard.



      I tried



      let swap a b = 
      match a,b with
      | a,b when a > b -> b,a
      | a,b when a <= b -> a,b


      I am trying to do this because in the following function call, I want to make sure that x is the bigger of the two variables.







      functional-programming ocaml






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 13:04







      chubbseN

















      asked Nov 22 '18 at 12:57









      chubbseNchubbseN

      184




      184
























          3 Answers
          3






          active

          oldest

          votes


















          2














          Without state, you cannot "swap" the values of the variables since the variables are immutable. Your best bet is to use a tuple and introduce new variables in the scope. Example:



          let diff a b =
          let (min, max) = if a <= b then (a, b) else (b, a)
          in max - min


          You can of course use the same identifiers and shadow the original variables:



          let diff a b =
          let (a, b) = if a <= b then (a, b) else (b, a)
          in b - a


          It doesn't really help with readability though.






          share|improve this answer































            3














            One easy way :



             let swap a b = 
            if (a>b) then (b,a)
            else (a,b)


            But this is not equivalent to the C code, your C code is swapping the value of the variable - this is how imperative language are doing.



            In Ocaml, there is no side-effect (except if you use reference to some int). This swap function will return a tuple whose members are always ordered (the first member will be always smaller than the second order).






            share|improve this answer































              0














              Just for reference, if you'd like to swap the values in two refs, it would look like the following:



              let swap a_ref b_ref =
              let a, b = !a_ref, !b_ref in
              a_ref := b;
              b_ref := a
              ;;


              which has the type val swap : 'a ref -> 'a ref -> unit.






              share|improve this answer























                Your Answer






                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: "1"
                };
                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',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53431572%2fswapping-variables-by-pattern-matching%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                2














                Without state, you cannot "swap" the values of the variables since the variables are immutable. Your best bet is to use a tuple and introduce new variables in the scope. Example:



                let diff a b =
                let (min, max) = if a <= b then (a, b) else (b, a)
                in max - min


                You can of course use the same identifiers and shadow the original variables:



                let diff a b =
                let (a, b) = if a <= b then (a, b) else (b, a)
                in b - a


                It doesn't really help with readability though.






                share|improve this answer




























                  2














                  Without state, you cannot "swap" the values of the variables since the variables are immutable. Your best bet is to use a tuple and introduce new variables in the scope. Example:



                  let diff a b =
                  let (min, max) = if a <= b then (a, b) else (b, a)
                  in max - min


                  You can of course use the same identifiers and shadow the original variables:



                  let diff a b =
                  let (a, b) = if a <= b then (a, b) else (b, a)
                  in b - a


                  It doesn't really help with readability though.






                  share|improve this answer


























                    2












                    2








                    2







                    Without state, you cannot "swap" the values of the variables since the variables are immutable. Your best bet is to use a tuple and introduce new variables in the scope. Example:



                    let diff a b =
                    let (min, max) = if a <= b then (a, b) else (b, a)
                    in max - min


                    You can of course use the same identifiers and shadow the original variables:



                    let diff a b =
                    let (a, b) = if a <= b then (a, b) else (b, a)
                    in b - a


                    It doesn't really help with readability though.






                    share|improve this answer













                    Without state, you cannot "swap" the values of the variables since the variables are immutable. Your best bet is to use a tuple and introduce new variables in the scope. Example:



                    let diff a b =
                    let (min, max) = if a <= b then (a, b) else (b, a)
                    in max - min


                    You can of course use the same identifiers and shadow the original variables:



                    let diff a b =
                    let (a, b) = if a <= b then (a, b) else (b, a)
                    in b - a


                    It doesn't really help with readability though.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 22 '18 at 13:17









                    BergiBergi

                    366k58546872




                    366k58546872

























                        3














                        One easy way :



                         let swap a b = 
                        if (a>b) then (b,a)
                        else (a,b)


                        But this is not equivalent to the C code, your C code is swapping the value of the variable - this is how imperative language are doing.



                        In Ocaml, there is no side-effect (except if you use reference to some int). This swap function will return a tuple whose members are always ordered (the first member will be always smaller than the second order).






                        share|improve this answer




























                          3














                          One easy way :



                           let swap a b = 
                          if (a>b) then (b,a)
                          else (a,b)


                          But this is not equivalent to the C code, your C code is swapping the value of the variable - this is how imperative language are doing.



                          In Ocaml, there is no side-effect (except if you use reference to some int). This swap function will return a tuple whose members are always ordered (the first member will be always smaller than the second order).






                          share|improve this answer


























                            3












                            3








                            3







                            One easy way :



                             let swap a b = 
                            if (a>b) then (b,a)
                            else (a,b)


                            But this is not equivalent to the C code, your C code is swapping the value of the variable - this is how imperative language are doing.



                            In Ocaml, there is no side-effect (except if you use reference to some int). This swap function will return a tuple whose members are always ordered (the first member will be always smaller than the second order).






                            share|improve this answer













                            One easy way :



                             let swap a b = 
                            if (a>b) then (b,a)
                            else (a,b)


                            But this is not equivalent to the C code, your C code is swapping the value of the variable - this is how imperative language are doing.



                            In Ocaml, there is no side-effect (except if you use reference to some int). This swap function will return a tuple whose members are always ordered (the first member will be always smaller than the second order).







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 22 '18 at 13:04









                            Pierre G.Pierre G.

                            3,3281721




                            3,3281721























                                0














                                Just for reference, if you'd like to swap the values in two refs, it would look like the following:



                                let swap a_ref b_ref =
                                let a, b = !a_ref, !b_ref in
                                a_ref := b;
                                b_ref := a
                                ;;


                                which has the type val swap : 'a ref -> 'a ref -> unit.






                                share|improve this answer




























                                  0














                                  Just for reference, if you'd like to swap the values in two refs, it would look like the following:



                                  let swap a_ref b_ref =
                                  let a, b = !a_ref, !b_ref in
                                  a_ref := b;
                                  b_ref := a
                                  ;;


                                  which has the type val swap : 'a ref -> 'a ref -> unit.






                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    Just for reference, if you'd like to swap the values in two refs, it would look like the following:



                                    let swap a_ref b_ref =
                                    let a, b = !a_ref, !b_ref in
                                    a_ref := b;
                                    b_ref := a
                                    ;;


                                    which has the type val swap : 'a ref -> 'a ref -> unit.






                                    share|improve this answer













                                    Just for reference, if you'd like to swap the values in two refs, it would look like the following:



                                    let swap a_ref b_ref =
                                    let a, b = !a_ref, !b_ref in
                                    a_ref := b;
                                    b_ref := a
                                    ;;


                                    which has the type val swap : 'a ref -> 'a ref -> unit.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Dec 1 '18 at 17:47









                                    mc10mc10

                                    8,44942851




                                    8,44942851






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53431572%2fswapping-variables-by-pattern-matching%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        404 Error Contact Form 7 ajax form submitting

                                        How to know if a Active Directory user can login interactively

                                        Refactoring coordinates for Minecraft Pi buildings written in Python