Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. The Weird and The Wonderful
  4. Interesting / strange code picked up from pluralsight training (functional programming)

Interesting / strange code picked up from pluralsight training (functional programming)

Scheduled Pinned Locked Moved The Weird and The Wonderful
csharpcomfunctionaltutorial
49 Posts 12 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I icemanind

    I knew you could have an @ sign in it. And it makes sense for @this because "this" is a reserved keyword in C#. Without the @ sign, naming a variable "this" would cause an error. But there is no keyword called "inVar", which is why I was confused about that one.

    R Offline
    R Offline
    raddevus
    wrote on last edited by
    #27

    Honestly, it was me being ignorant. However, you've made me think about this and I get the point now. It sounds like I'm being sarcastic but I'm really not. I know this thread has been odd but it has really made me rethink and firstThink a number of things. :thumbsup:

    1 Reply Last reply
    0
    • R raddevus

      Eddy Vluggen wrote:

      or due to OO and your result being an object?

      A valid point. :(( But, blithely I roll on. :laugh: Let's see. what else could I do to a String?... :rolleyes:

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #28

      :laugh: Have fun :thumbsup:

      Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^] "If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.

      1 Reply Last reply
      0
      • R raddevus

        Ohh...look...I've really gone crazy with this now.

        public static class Helper{
        public static T Tee(
        this T @inVal,
        Action act){
        act(@inVal);
        return @inVal;
        }

        public static Byte\[\] GetBytes( this String @inVal){
        	Byte \[\] outBytes = new Byte\[@inVal.Length\];
        	int loopCount = 0;
        	foreach (Char c in @inVal){
        		outBytes\[loopCount\] = Convert.ToByte(c);
        		loopCount++;
        	}
        	return outBytes;
        }
        
        public static String DisplayBytes(this byte\[\] inBytes){
        	String outVal = String.Empty;
        	foreach (Byte b in inBytes){
        		outVal += Convert.ToString($"{b} ");
        	}
        	return outVal;
        }
        

        }

        Try it like this and you get before and after again:

        "What up!"
        .Tee(Console.WriteLine)
        .GetBytes()
        .DisplayBytes()
        .Tee(Console.WriteLine);

        Output looks like:

        What up!
        87 104 97 116 32 117 112 33

        :cool: Well, it's fun.

        R Offline
        R Offline
        Richard Deeming
        wrote on last edited by
        #29

        Quote:

        public static Byte[] GetBytes( this String @inVal){
        Byte [] outBytes = new Byte[@inVal.Length];
        int loopCount = 0;
        foreach (Char c in @inVal){
        outBytes[loopCount] = Convert.ToByte(c);
        loopCount++;
        }
        return outBytes;
        }

        That should probably be:

        public static Byte[] GetBytes( this String @inVal ) => System.Text.Encoding.UTF8.GetBytes(@inVal);

        Remember, some characters aren't single bytes. :)


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        R 1 Reply Last reply
        0
        • R Richard Deeming

          Quote:

          public static Byte[] GetBytes( this String @inVal){
          Byte [] outBytes = new Byte[@inVal.Length];
          int loopCount = 0;
          foreach (Char c in @inVal){
          outBytes[loopCount] = Convert.ToByte(c);
          loopCount++;
          }
          return outBytes;
          }

          That should probably be:

          public static Byte[] GetBytes( this String @inVal ) => System.Text.Encoding.UTF8.GetBytes(@inVal);

          Remember, some characters aren't single bytes. :)


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          R Offline
          R Offline
          raddevus
          wrote on last edited by
          #30

          Richard Deeming wrote:

          Remember, some characters aren't single bytes

          Very good. A very amateur mistake by me. :-O I was excited about the idea and didn't think about the code that is already there for me. Lame! Thanks again! :thumbsup:

          1 Reply Last reply
          0
          • Sander RosselS Sander Rossel

            Like Richard, I was thinking of an extension method. What you have there is pretty hard to read, took me a while to figure out what it does (due to the nested Tee, which is not a very helpful name either). I'm all for chaining though, that's what LINQ does too (which is pretty functional). Applying functional principles (but remembering C# is not a functional language) really helped me write cleaner and more succinct code. Although not everyone agrees with me, some people prefer their foreach loops and can't read lambda's :sigh: One thing I've learned, and taken to heart, a function has input and predictable output (no side-effects or state!). At some point you're going to have state and output, of course, but that's reserved for special classes. To give an example (from the top of my head, ignore bad practices such as public fields):

            public class BadClass
            {
            public string s;
            public void BadClass(string s)
            {
            this.s = s;
            }

            public void DoubleString()
            {
            s = s + s;
            }
            }

            // Usage
            var bc = new BadClass("Hello");
            bs.DoubleString();
            Console.WriteLine(bc.s); // HelloHello

            public class GoodClass
            {
            public void DoubleString(string s)
            {
            return s + s;
            }
            }

            // Usage
            var gc = new GoodClass();
            var s = gc.DoubleString("Hello");
            Console.WriteLine(s); // HelloHello

            It's a bit contrived, but you'd be amazed at how often I've seen the BadClass implementation (equivalent) of this. People just love their state and side effects. But then again, I've worked on old VB applications with old VB programmers... As coincidence would have it Packt offers a free Functional C#[^] eBook today, may be interesting (haven't read it myself).

            Best, Sander Continuous Integration, Delivery, and Deployment arrgh.js - Bringing LINQ to JavaScript Object-Oriented Programming in C# Succinctly

            B Offline
            B Offline
            BillWoodruff
            wrote on last edited by
            #31

            Hi Sander, Evidently PackT changes which book is free every day, so that one is no longer free. cheers, Bill

            «... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12

            Sander RosselS 1 Reply Last reply
            0
            • R raddevus

              I was watching a very good intro to Functional programming on PluralSight (Functional Programming with C# | Pluralsight[^]) and the author / presenter created the following method (mine has altered var names).

              public static class Helper{
              public static T Tee(
              T @inVal,
              Action act){
              act(@inVal);
              return @inVal;
              }
              }

              Now you can call that method like the following:

              Helper.Tee("test", Console.WriteLine);
              Helper.Tee(3.238, Console.WriteLine);
              Helper.Tee (new {garbage="super"},Console.WriteLine);

              Here's the output:

              test
              3.238
              { garbage = super }

              It's loosely based on the following idea (why it's named Tee): tee (command) - Wikipedia[^] Just thought it was an interesting example and it made me think differently about things. After all these years of OOP I'm beginning to see the real value in the Functional paradigm*. *Obviously the included sample is not a huge example of Functional programming in and of itself.

              B Offline
              B Offline
              BillWoodruff
              wrote on last edited by
              #32

              Hi, Raddevus, Really enjoying this discussion ! It would be interesting if you could, somehow:

              public static T TeeHee(this T tee, params Func[] funcs)
              {

              foreach (var func in funcs)
              {
                 // ???????
              }
              
              return tee;
              

              }

              But, the obvious problem is that all the funcs have to have the same return type. cheers, Bill

              «... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12

              R R M 3 Replies Last reply
              0
              • B BillWoodruff

                Hi Sander, Evidently PackT changes which book is free every day, so that one is no longer free. cheers, Bill

                «... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12

                Sander RosselS Offline
                Sander RosselS Offline
                Sander Rossel
                wrote on last edited by
                #33

                Yeah, that's why I said "today" yesterday :)

                Best, Sander Continuous Integration, Delivery, and Deployment arrgh.js - Bringing LINQ to JavaScript Object-Oriented Programming in C# Succinctly

                1 Reply Last reply
                0
                • B BillWoodruff

                  Hi, Raddevus, Really enjoying this discussion ! It would be interesting if you could, somehow:

                  public static T TeeHee(this T tee, params Func[] funcs)
                  {

                  foreach (var func in funcs)
                  {
                     // ???????
                  }
                  
                  return tee;
                  

                  }

                  But, the obvious problem is that all the funcs have to have the same return type. cheers, Bill

                  «... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12

                  R Offline
                  R Offline
                  Richard Deeming
                  wrote on last edited by
                  #34

                  Func<T, TResult> is covariant[^] on the return type, so you could pass in functions which returned a more derived type than the declared return type.

                  public static T TeeHee<T>(this T tee, params Func<T, object>[] funcs)
                  {
                  foreach (var func in funcs)
                  {
                  object x = func(tee);
                  // ???
                  }

                  return tee;
                  

                  }

                  42.TeeHee(
                  i => i, // Func<int, int>
                  i => $"The answer is {i}", // Func<int, string>
                  i => new Answer(i) // Func<int, Answer>
                  );

                  The more important question would be, what are you intending to do with the returned values?


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  B 1 Reply Last reply
                  0
                  • B BillWoodruff

                    Hi, Raddevus, Really enjoying this discussion ! It would be interesting if you could, somehow:

                    public static T TeeHee(this T tee, params Func[] funcs)
                    {

                    foreach (var func in funcs)
                    {
                       // ???????
                    }
                    
                    return tee;
                    

                    }

                    But, the obvious problem is that all the funcs have to have the same return type. cheers, Bill

                    «... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12

                    R Offline
                    R Offline
                    raddevus
                    wrote on last edited by
                    #35

                    You're saying so you could run a number of methods (funcs) (in the foreach loop), right? That would be interesting. Once you start doing this stuff it inspires you to see everything this way. :thumbsup:

                    B 1 Reply Last reply
                    0
                    • R raddevus

                      Eddy Vluggen wrote:

                      Like a decorator..

                      cue Madonna

                      ...touched for the very first time...

                      :laugh: I could not pass that up. Ignoring the bad joke (if possible) I think your point is really interesting, because it is like a decorator. Also, in an effort to completely beat this dead horse, how about the following addition? If, nothing else, the added method has a great name : see SpaceOut.

                      public static class Helper{
                      public static T Tee(
                      this T @inVal,
                      Action act){
                      act(@inVal);
                      return @inVal;
                      }

                      public static Byte\[\] GetBytes( this String @inVal){
                      	Byte \[\] outBytes = new Byte\[@inVal.Length\];
                      	int loopCount = 0;
                      	foreach (Char c in @inVal){
                      		outBytes\[loopCount\] = Convert.ToByte(c);
                      		loopCount++;
                      	}
                      	return outBytes;
                      }
                      
                      public static String DisplayBytes(this byte\[\] inBytes){
                      	String outVal = String.Empty;
                      	foreach (Byte b in inBytes){
                      		outVal += Convert.ToString($"{b:D3} ");
                      	}
                      	return outVal;
                      }
                      
                      public static String SpaceOut(this string @inVal){
                      	StringBuilder spacedItem = new StringBuilder();
                      
                      	foreach (Char c in @inVal){
                      		spacedItem.Append($" {c}    ");
                      	}
                      	Console.WriteLine(spacedItem.ToString());
                      	return @inVal;
                      }
                      

                      }

                      Now you can do this:

                      "What up!"
                      .Tee(Console.WriteLine)
                      .SpaceOut()
                      .GetBytes()
                      .DisplayBytes()
                      .Tee(Console.WriteLine);

                      And you will get the following:

                      What up!
                      W h a t u p !
                      087 104 097 116 032 117 112 033

                      Additionally interesting (or not) is that SpaceOut simply passes the input string along with no change since you only want the input to be printed with the extra spaces but don't want the output altered in this case. I got a million of 'em! :laugh:

                      Sander RosselS Offline
                      Sander RosselS Offline
                      Sander Rossel
                      wrote on last edited by
                      #36

                      SpaceOut has a side-effect and is not functional by definition :) It seems you're spacing out :laugh:

                      Best, Sander Continuous Integration, Delivery, and Deployment arrgh.js - Bringing LINQ to JavaScript Object-Oriented Programming in C# Succinctly

                      R 1 Reply Last reply
                      0
                      • B BillWoodruff

                        Hi, Raddevus, Really enjoying this discussion ! It would be interesting if you could, somehow:

                        public static T TeeHee(this T tee, params Func[] funcs)
                        {

                        foreach (var func in funcs)
                        {
                           // ???????
                        }
                        
                        return tee;
                        

                        }

                        But, the obvious problem is that all the funcs have to have the same return type. cheers, Bill

                        «... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12

                        M Offline
                        M Offline
                        Marc Clifton
                        wrote on last edited by
                        #37

                        Replace params Func[] funcs simply with >> and you're good to go. Marc

                        Latest Article - Contextual Data Explorer Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

                        B 1 Reply Last reply
                        0
                        • R raddevus

                          I was watching a very good intro to Functional programming on PluralSight (Functional Programming with C# | Pluralsight[^]) and the author / presenter created the following method (mine has altered var names).

                          public static class Helper{
                          public static T Tee(
                          T @inVal,
                          Action act){
                          act(@inVal);
                          return @inVal;
                          }
                          }

                          Now you can call that method like the following:

                          Helper.Tee("test", Console.WriteLine);
                          Helper.Tee(3.238, Console.WriteLine);
                          Helper.Tee (new {garbage="super"},Console.WriteLine);

                          Here's the output:

                          test
                          3.238
                          { garbage = super }

                          It's loosely based on the following idea (why it's named Tee): tee (command) - Wikipedia[^] Just thought it was an interesting example and it made me think differently about things. After all these years of OOP I'm beginning to see the real value in the Functional paradigm*. *Obviously the included sample is not a huge example of Functional programming in and of itself.

                          M Offline
                          M Offline
                          Marc Clifton
                          wrote on last edited by
                          #38

                          [Class-less Coding - Minimalist C# and Why F# and Function Programming Has Some Advantages](https://www.codeproject.com/Articles/1200375/Class-less-Coding-Minimalist-Csharp-and-Why-Fsharp#Second,Fluency3) Shameless plug, but if you want to look at doing functional programming in C# beyond just Action and Func, you might want to take a look at that.

                          Latest Article - Contextual Data Explorer Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

                          R 1 Reply Last reply
                          0
                          • Sander RosselS Sander Rossel

                            SpaceOut has a side-effect and is not functional by definition :) It seems you're spacing out :laugh:

                            Best, Sander Continuous Integration, Delivery, and Deployment arrgh.js - Bringing LINQ to JavaScript Object-Oriented Programming in C# Succinctly

                            R Offline
                            R Offline
                            raddevus
                            wrote on last edited by
                            #39

                            I thought a side effect would be to affect some property of the object?? I don't see where SpaceOut is be doing that. Let me know what you're thinking so I can learn. thx

                            R 1 Reply Last reply
                            0
                            • M Marc Clifton

                              [Class-less Coding - Minimalist C# and Why F# and Function Programming Has Some Advantages](https://www.codeproject.com/Articles/1200375/Class-less-Coding-Minimalist-Csharp-and-Why-Fsharp#Second,Fluency3) Shameless plug, but if you want to look at doing functional programming in C# beyond just Action and Func, you might want to take a look at that.

                              Latest Article - Contextual Data Explorer Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

                              R Offline
                              R Offline
                              raddevus
                              wrote on last edited by
                              #40

                              Thanks very much. I will read that later today. I was looking for just such a resource. Love it when the answers just crash into me without me having to exert any energy. :laugh:

                              1 Reply Last reply
                              0
                              • R raddevus

                                I thought a side effect would be to affect some property of the object?? I don't see where SpaceOut is be doing that. Let me know what you're thinking so I can learn. thx

                                R Offline
                                R Offline
                                Richard Deeming
                                wrote on last edited by
                                #41

                                In functional terms, writing to the console is a side-effect. :)


                                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                R 1 Reply Last reply
                                0
                                • R Richard Deeming

                                  In functional terms, writing to the console is a side-effect. :)


                                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                  R Offline
                                  R Offline
                                  raddevus
                                  wrote on last edited by
                                  #42

                                  Ah, yes. That explains. thanks, very much. However, I still kind of secretly like that SpaceOut method, but don't tell everyone because they'll think I'm not all functional-minded. :) Seriously though, that was good to learn because it makes me think the right way about functional programming that it should be just like a mathematical expression. Do the thing, return the value. :thumbsup: ;)

                                  Sander RosselS 1 Reply Last reply
                                  0
                                  • R Richard Deeming

                                    Func<T, TResult> is covariant[^] on the return type, so you could pass in functions which returned a more derived type than the declared return type.

                                    public static T TeeHee<T>(this T tee, params Func<T, object>[] funcs)
                                    {
                                    foreach (var func in funcs)
                                    {
                                    object x = func(tee);
                                    // ???
                                    }

                                    return tee;
                                    

                                    }

                                    42.TeeHee(
                                    i => i, // Func<int, int>
                                    i => $"The answer is {i}", // Func<int, string>
                                    i => new Answer(i) // Func<int, Answer>
                                    );

                                    The more important question would be, what are you intending to do with the returned values?


                                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                    B Offline
                                    B Offline
                                    BillWoodruff
                                    wrote on last edited by
                                    #43

                                    Another brilliant gem ! thanks, Bill

                                    «... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12

                                    1 Reply Last reply
                                    0
                                    • M Marc Clifton

                                      Replace params Func[] funcs simply with >> and you're good to go. Marc

                                      Latest Article - Contextual Data Explorer Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

                                      B Offline
                                      B Offline
                                      BillWoodruff
                                      wrote on last edited by
                                      #44

                                      Nice ! thanks, Bill

                                      «... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12

                                      1 Reply Last reply
                                      0
                                      • R raddevus

                                        You're saying so you could run a number of methods (funcs) (in the foreach loop), right? That would be interesting. Once you start doing this stuff it inspires you to see everything this way. :thumbsup:

                                        B Offline
                                        B Offline
                                        BillWoodruff
                                        wrote on last edited by
                                        #45

                                        This thread, and the responses to it, are the kind of back-and-forth that makes CP so valuable to me ! thanks, again, to your ever curious mind for starting it. cheers, Bill

                                        «... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12

                                        1 Reply Last reply
                                        0
                                        • R raddevus

                                          Ah, yes. That explains. thanks, very much. However, I still kind of secretly like that SpaceOut method, but don't tell everyone because they'll think I'm not all functional-minded. :) Seriously though, that was good to learn because it makes me think the right way about functional programming that it should be just like a mathematical expression. Do the thing, return the value. :thumbsup: ;)

                                          Sander RosselS Offline
                                          Sander RosselS Offline
                                          Sander Rossel
                                          wrote on last edited by
                                          #46

                                          I can recommend learning Haskell, a pure functional language. In Haskell all I/O is considered a side-effect (database actions, drawing, printing to console, writing a file, etc.). If you're doing any I/O in Haskell your function must return the special System.IO object. Here's a nice example of Hello World in Haskell[^]. I don't know Haskell very well myself, just followed a course at University, but it certainly changed how I think about my code and it taught me some nice functional concepts :) My favorite example of how nice, readable and succinct a functional programming and Haskell can be is an implementation of the quick sort algorithm:

                                          qsort [] = []

                                          ++ qsort bigger

                                          where
                                          smaller = [a | a <- xs, a <= x]
                                          bigger = [a | a <- xs, a > x]

                                          Best, Sander Continuous Integration, Delivery, and Deployment arrgh.js - Bringing LINQ to JavaScript Object-Oriented Programming in C# Succinctly

                                          R 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups