Thursday, December 29, 2011

Someone want to explain functional programming to me?

Today I watched this presentation by Runar Bjarnason on Functional Programming and attempted to make an example in code that showed off both a High Order Function and Recursion. I'm pretty sure I've screwed it up. I'm going to have to ask some of the guys at work what I did wrong on Tuesday when AMD is back from break, but in the meantime, here is my code. It is an expansion of the example I started here. I paint the screen with five German numbers in a view like so:

@model List<string>

<h1>Even German Numbers Of Single Digit Length:</h1>

@foreach(string item in Model)

{

   <p>@item</p>

}

 
 

This drives my view. Here I am trying to do some looping. I know this has to be the wrong way to go about it and the wrong way to maintain the numeric state. Nuts. It has been suggested to me (I have notes here) that a Func may be passed about and progressively change shape as it moves based on the things that touch it. I'm not sure how to represent this.

using System;

using System.Collections.Generic;

using System.Web.Mvc;

using Core;

namespace FrontEnd.Controllers

{

   public class HomeController : Controller

   {

      public ActionResult Index()

      {

         List<string> foo = new List<string>();

         Func<KeyValuePair<Int16, Int16>, KeyValuePair<Int16, string>> bar =

               DeutschDigitStateMachine.ChangeShape;

         KeyValuePair<Int16,string> baz = bar(new KeyValuePair<Int16, Int16>(0,0));

         while (baz.Key < 10)

         {

            if (baz.Key < 10) foo.Add(baz.Value);

            baz = bar(new KeyValuePair<Int16, Int16>(baz.Key, 2));

         }

         return View(foo);

      }

   }

}

 
 

Here is my High Order Function. TryToGiveGermanNameForSingleDigit is what it was in the previous code.

using System;

using System.Collections.Generic;

namespace Core

{

   public static class DeutschDigitStateMachine

   {

      public static KeyValuePair<Int16,string> ChangeShape(KeyValuePair<Int16,Int16>

            halvesOfDigit)

      {

         Int16 digit = Convert.ToInt16(halvesOfDigit.Key + halvesOfDigit.Value);

         Func<Int16, string> convertInteger =

               DigitToDeutschTranslator.TryToGiveGermanNameForSingleDigit;

         return new KeyValuePair<Int16, string>(digit,convertInteger(digit));

      }

   }

}

 
 

I end up with the following HTML which means that it works. And yet, I feel I've screwed up the implementation. Any thoughts anyone?

<h1>Even German Numbers Of Single Digit Length:</h1>

<p>null</p>

<p>zwei</p>

<p>vier</p>

<p>sechs</p>

<p>acht</p>

No comments:

Post a Comment