Elm – Mapping Anonymous Functions

In my prior post I wrote about creating a recursive function in Elm to iterate through a list of records and update a single record that met the search criteria.

I’ll admit that I was quite pleased with my solution not only because I had wanted to figure it out before looking at the instructor’s answer, but my implementation seemed particularly Elm-like.

So when I looked at the instructor’s solution, wondering how he would implement, I was pleasantly shocked (and a bit humbled) to see an entirely different way to implement iterate through a list an modify a particular record that didn’t use recursion.

Before I show you the instructor’s code I’ll need to talk about two things–how to create anonymous functions in Elm and Elm’s map function.

An anonymous function is a function that isn’t assigned to a particular identifier. They’re usually defined in-line. They’re parenthesized and the content is prefixed with a backslash. Anonymous functions are often used as arguments passed to higher-order functions or as part of a result of a higher-order function that needs to return a function.

The syntax for an anonymous function is:

(\param1 param2 ... -> -- Body)

(\x y -> x * y)
-- 6 : number

List.map (\n -> sayHello n) ["Alice", "Bob"]
-- ["Hello Alice", "Hello Bob"] : List String

By themselves anonymous functions are not much. But when you combine them with other functions they become much more powerful.

The map function can be used to apply a function to every element of a list or an array.

map : (a -> b) -> List a -> List b

map sqrt [1, 4, 9] == [1, 2, 3]
map not [True, False, True] == [False, True, False]

So map appears to have list and array iteration built-in. But there’s no standard Elm function that can examine the elements of a record, compare one element to the criteria, and modify another element based on the results of that evaluation. But with anonymous functions we can create a function to do that.

From the last example you see that it’s possible to create an anonymous function that map can use to modify a list of items. So let’s look at the instructor’s solution.

First, here’s the type alias of the model he’s passing in to his edit function. The model contains a list of players, the playerId of the player whose name we want to change, and the new name.

type alias Model =
    { players : List Player
    , name : String
    , playerId : Maybe Int
    }

type alias Player =
    { id : Int
    , name : String
    , points : Int
    }

Here’s his edit function.

edit : Model -> Int -> Model
edit model id =
    let 
        newPlayers =
            List.map
                (\player ->;
                    if player.id == id then
                        { player | name = model.name }
                    else
                        player
                )
                model.players
    in
        { model 
            | players = newPlayers
            , name = ""
            , playerId = Nothing
        }

The edit function takes a Model and an Int as parameters and returns a new Model (I like this much better than my way of passing in a Player record and a List of Player. It seems much cleaner since the Model contains everything you need).

The let/in construct allows you to create local variables in the let section which you can use in expressions in the in section.

A newPlayers list is created in the let section using map with an anonymous function. Each player record is passed into the anonymous function as a parameter. If the player.id matches edit’s id parameter then the player’s name is changed to the new name stored in model.name. If not, the unchanged player record is returned by the anonymous function.

A new model is created in the in section with the following changes and returned.

  • The old players list is replaced with newPlayers
  • name is set to an empty string
  • playerId is set to Nothing

I have to admit that I was both pleased and humbled to see this solution.

I’m pleased because it seemed so much more elegant and Elm-like than my recursive function (which I thought and still think is pretty cool). Also, the way map and anonymous functions are applied here could be used if my model contained other instances of player name in other lists that needed to be updated at the same time.

I’m humbled because looking at the instructor’s solution made me realize how much I don’t know about Elm and functional programming. When learning a new programming language, especially something as radical as Elm, I think I tend to approach it with the constructs and mindset of the old languages I know. It takes a while for me to “unlearn” what I know in order to embrace the new paradigm correctly (I hope).

I’m comforted by the fact that I’m just at the start of the journey, excited about what I’ll see along the way and wondering where I’ll end up. I’m looking forward to finding out what I don’t know.

Posted in Software Development | Tagged , , | Leave a comment

Elm – Recursive Functions

In one of the Elm For Beginners exercises I have to update a player record’s name field with the modified player name and all I have is the playerId to search on.

Here are the Elm type alias for the Model and the Player

type alias Model =
    { players : List Player
    , name : String
    , playerId : Maybe Int
    }

type alias Player =
    { id : Int
    , name : String
    , points : Int
    }

If I were writing this in C# I’d probably have the Player objects stored in a generic List. To modify PlayerId’s name I’d probably use a foreach statement to iterate through the list. When I found the Player object who’s id matched PlayerId, I’d change the player’s name.

public int PlayerId;
public string Name;
public List<Player> Players;

public class Player
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Points { get; set; }
}

// 1. Code to create Players list and populate with Players
// 2. Code to set Name to player's new name
// 3. Code to set PlayerId of player whose name you want to update

foreach (Player p in Players)
{
    if p.Id = PlayerId {
        p.Name = Name;
    }
}

But Elm doesn’t have control structures like for, foreach, while, or do-while. So how do I iterate over the record elements in the list below and modify the one player record that meets the criteria?

[ { id = 2, name = "Robin Maya", points = 0 }
  , id = 1, name = "Katie Maya", points = 0 }
  , id = 0, name = "Bill Maya", points = 0 } ] 

From working with Clojure and reading Functional Programming for the Object-Oriented Programmer I knew that is was possible to extract the items in a list. Elm provides you with head function to extract the first element of a list.

head : List a -> Maybe a
head [1, 2, 3] == Just 1
head [] == Nothing

And a tail function to extract the rest of the list.

tail : List a -> Maybe (List a)
tail [1, 2, 3] == Just [2, 3]
tail [] == Nothing

The type annotation before the head and tail examples is an Elm convention that makes is easier at a glance to determine a function’s inputs and outputs and also easier to debug compiler warnings.

Both functions take a list (“List a”) as input and output a single element of that list (“Maybe a” for head) or the remainder of the list (“Maybe (List a) for tail”).

The “Maybe” in this type annotation indicates that in certain situations, like when an empty list is passed as a parameter, nothing might be returned (in fact, Nothing is returned).

Since Elm doesn’t support null values it uses the union types of Maybe, Just, and Nothing to handle situations like this (I’ll probably do a blog post about these types at a later date as I try to understand them better).

So using head and tail I could systematically extract the values of a list for review. If I take the example Elm list with the three Player records in it that I showed previously and applied successive head and tail functions to it I would get this:

#1
head == { id = 2, name = "Robin Maya", points = 0 }
tail == [ { id = 1, name = "Katie Maya", points = 0 }
          , id = 0, name = "Bill Maya", points = 0 } ]

#2
head == { id = 1, name = "Katie Maya", points = 0 }
tail == [ { id = 1, name = "Bill Maya", points = 0 } ]

#3
head == { id = 1, name = "Bill Maya", points = 0 }
tail == []

So I can extract individual list elements but one question remains–what mechanism do I use to leapfrog my way through the list since Elm doesn’t provide foreach or do-while control structures?

Some thinking and googling lead me to this page which explained how to create recursive functions in Elm.

To explain how a recursive function works here’s an example of how to calculate the factorial of a number using recursion. In mathematics, the factorial n! of a non-negative number n is the product of all positive integers less than or equal to n. For example,

5! = 5 x 4 x 3 x 2 x 1 = 120

The Elm function to calculate the factorial of a number would be:

import Html exposing (..)

main = Html.text (toString (factorial 5))

factorial : Int -> Int
factorial int =
    case int of
        0 ->
            1
        _ ->
            int * factorial (int - 1)

The factorial function type annotation (line 5) indicates that this function takes an Int as a parameter and returns an Int. The case statement in the body of the function (lines 6-10) uses pattern matching to determine what to do with the parameter value passed into the function:

  • If the value of int is zero the functions returns a value of one
  • Otherwise, for any other value (“_” acts as a wildcard) the function calls itself again, subtracting one from the current value of int. The value returned from this function call is multiplied by the original value of int.

In the example above, calling the factorial function with the parameter of 5 makes five recursive function calls.

factorial 5
    5 * factorial 4
        4 * factorial 3
            3 * factorial 2
                2 * factorial 1
                    1 * factorial 0
                        1

Which yields the value of 120.

Back to my original problem–I have to update one of the records in the list using the player’s id.

[ { id = 2, name = "Robin Maya", points = 0 }
  , id = 1, name = "Katie Maya", points = 0 }
  , id = 0, name = "Bill Maya", points = 0 } ] 

So I wrote a recursive updatePlayer function to do that.

updatePlayer : Player -> List Player -> List Player
updatePlayer player players =
    case players of
        [] ->
            []
        x :: xs ->
            if x.id == player.id then
                { x | name = player.name } :: xs
            else
                updatePlayer player xs

The function takes two parameters–the first is a single player object containing the id of the player to update and their new name. The second is a list of current players. The function returns a list of updated players.

The case statement uses pattern matching to determine what to do with the list that’s passed as a parameter into the function. If the list is empty, it simply returns and empty list (lines 4-5).

The pattern on line 6 splits the list into a head and a tail. The head (a record) is assigned to x and the tail (a list) is assigned to xs. If the id of the head record is equal to the id in the player record a new player record is created with an updated player name (obtained from the player record) using the following format:

newRecordName =
    { oldRecordName | fieldName1 = newFieldValue1
                    , filedName2 = newFieldValue2
                    ...
    }

Rather than assigning this newly created record (Elm data is immutable) I simply it after using the cons statement (::) to add it to the front of the list stored in xs

If the id of the head record is not equal to the id in the player record then I recursively call the updatePlayer function again, passing in the player object and the tail stored in xs as the list.

This first attempt of updatePlayer has an error in it. When passing in the Before list the function returned the After list. The player’s name was updated from “Katie” to “Kathleen” but I lost one of my records. Rather than retaining a record that didn’t match the player id the function appeared to be throwing it away until if found a match.

Before:
[ { id = 2, name = "Robin Maya", points = 0 }
  , id = 1, name = "Katie Maya", points = 0 }
  , id = 0, name = "Bill Maya", points = 0 } ]

After:
[ { id = 1, name = "Kathleen Maya", points = 0 }
  , id = 0, name = "Bill Maya", points = 0 } ]

I spent some time trying to figure out why this was happening but ran up against my limited knowledge of Elm and my unfamiliarity with functional programming. I thought about also passing in an empty list as one of the parameters and using it to store head records as I iterated through the list but that seemed kludgy.

So I did the next best thing–I decided to sleep on it and return to the problem the next day.

Fifteen minutes after sitting down at the keyboard the next morning I discovered my omission.

-- Original
updatePlayer : Player -> List Player -> List Player
updatePlayer player players =
    case players of
        [] ->
            []
        x :: xs ->
            if x.id == player.id then
                { x | name = player.name } :: xs
            else
                updatePlayer player xs

-- Modified
updatePlayer : Player -> List Player -> List Player
updatePlayer player players =
    case players of
        [] ->
            []
        x :: xs ->
            if x.id == player.id then
                { x | name = player.name } :: xs
            else
                x :: updatePlayer player xs

Compare the recursive function call on lines 11 and 23. Line 11 discards the unmatched head record when calling updatePlayer again while line 23 uses the cons (::) function to “stitch” the unmatched head record to the whatever results are returned by subsequent calls to updatePlayer.

I was quite pleased with myself for about fifteen minutes. Not only had I figured out how to iterate through a list using Elm pattern matching but I was also one step closer to grokking the immutable nature of data in Elm.

But then I reviewed the lesson’s answer to see the instructor’s solution and discovered another way to accomplish the same thing using two new Elm functions and no recursion. It was a bit humbling. I’ll write about it in my next post.

Helpful links

Posted in Software Development | Tagged , , | Leave a comment

Elm

I’m 78% of the way through Elm For Beginners, a free course about the Elm programming language. I first read about Elm in Seven More Languages in Seven Weeks but did nothing with it until this week.

My reasons for learning Elm are simple:

  • It compiles down to HTML, CSS, and JavaScript, the three languages used to build web applications
  • It’s a functional reactive language with strong types and immutable data structures

Though I’ve had some experience with HTML and CSS, web development isn’t the first thing that bubbles to the top when I consider the software development that I’ve done in the past. I fiddled around with JavaScript because it’s become the lingua franca on the web and I felt I should know it better but there are some things about it that leave me cold.

I’ve read a lot about functional languages in the past, about how their immutable data and lack of side effects help you develop code that is easily maintained, easily testable, and easily refactored. Given that most of my coding has been in C# .NET over the past years I figured I would check out F#, Microsoft’s functional language.

But when I looked at F# I just wasn’t excited about it (I still might use it for cross-platform development with Xamarin down the road) and I had this nagging feeling that I should beef up the web development side of my resume but I didn’t want to start at the HTML/CSS/JavaScript level.

So I took another look at the Elm, checked out the home page and some of the documentation and decided that this is the language that I want to use for creating web front ends. Down the road I can figure out how to make it interop with either  ASP.NET MVC or learn another functional language like Elixir, combined with the Phoenix framework.

I’ll leave you with Richard Feldman’s excellent Introduction to Elm.

Posted in Software Development | Tagged , , | Leave a comment

Do!

Andrew Scott reads Sol Lewitt’s April 14th, 1965 letter to Eva Hesse.

Benedict Cumberbatch reads Sol Lewitt’s April 14th, 1965 letter to Eva Hesse (added 10/20/16).

I love watching and listening to both actors but personally I prefer Andrew Scott’s reading.

Posted in Other | Tagged | Leave a comment

Chris’ Feedback on Campaign Puppets

I emailed Chris Crawford to get his feedback on my Campaign Puppets game idea. He replied that the design had several problems:

  1. Previous games of this type have failed.
  2. Vague or unknown voter preference algorithms make scoring and victory determination difficult if not impossible and/or reliant on chance.
  3. Large icon vocabulary increases player confusion.
  4. How do you show relationship between words, i.e. grammar
  5. Large vocabulary leads to problems with language comprehension algorithms

Chris raises some very good points which I’ll try to start addressing below.

Prior Failures (#1)

Previous games in this genre have appealed to a niche audience, those interested in political elections, and focused on resource management–opening campaign offices, running ads, raising funds, giving speeches–and moving the candidate between the states to raise your poll results.

Campaign Puppets focuses on “People not Things,” specifically on the primary candidates and the one area where their direct actions can affect their campaigns–the candidate debates. The game will still appeal to a niche audience (though the debate audience might be larger than the campaign manager audience) and the focus is on conversation which, in today’s political climate, includes trash talk.

There are many more things that have to be done before it can be determined if this design can be judged a success of a failure (some of which are listed below). Right now Campaign Puppets looks like an interesting experiment. Several things need to be hashed out before it can become a reality.

Voter Preference Algorithms (#2)

I haven’t even thought about this until Chris mentioned it. My previous attempts to create polling algorithms for Camelot were incomplete but reviewing them gave me an appreciation of how difficult this work might be.

For Campaign Puppets I want a real-time display of candidate rankings during the debate. At the end of the debatewinner, which means the electorate believes that they should be the party’s candidate in the general election.

IMG_0006 43%
IMG_0007 22%
IMG_0008 17%
IMG_0009 13%
IMG_0010 5%

In order to do this I’ll need to know how candidate reactions are affecting the electorate which means I’ll need an electorate population with positions on certain issues.

I’ve got some ideas building on my previous work (see the link at the beginning of this section). I’ll write up another blog post specifically addressing this issue.

Large Icon Vocabulary (#3)

The icons displayed in the inverse parser are not the final icons but merely placeholders. They’re there to give the player an idea of how and where they’ll create a candidate’s responses. At this point I don’t know what the final “words” will be or how many there will be.

Whatever the final word count turns out to be, I believe that an inverse parser will reduce confusion since it puts the player in the driver’s seat, allowing them visually construct sentences from only the appropriate words for that particular part of the sentence.

Here’s an example of an inverse parser in action creating a sentence from the Storytron version of Siboot.

storytron-siboot-inverse-parser-1

  1. You’re given a list of valid choices for the sentence’s Verb.
  2. You’re given a list of valid choices for the sentence’s Direct Object (in this case it’s characters who aren’t at the current location).
  3. Piece by piece you construct a complete sentence from only valid options. Here we’re about the select the final word of the sentence before having the character “say” it.

The video below shows the Storytron Siboot inverse parser in action. You’ll see how easy it is to undo previous selections as your mind changes and that at no point should the user be unclear as to what options they can select.

This video of Chris’ work on the latest incarnation of Siboot shows how the same type of inverse parser would work with icons.

[INSERT VIDEO HERE]

Grammar (#4)

Grammar is the syntax and structure of a language. In Storytron the language was sentence-based, with each sentence being composed of a Subject, a Verb, and one or more storyteller-configurable WordSockets. Here’s an example, the “offer to reveal” verb illustrated in the inverse parser above.

storytron-siboot-verb-properties-1

The focus in Storytron was conversations between characters. Campaign Puppets is more about swaying an audience, about rhetoric and debate. But it still boils down to what does the candidate say in reply.

I’ll have to give this some additional thought and see what the verbs might be which will help me determine whether candidate replies can fit into the Storytron sentence model (which is quite flexible) or whether I have to invent something new.

Language Comprehension Algorithms (#5)

Teen Talk had a very simple language–”X says that s/he likes Y by amount Z”–and the code behind that language reflected it’s simplicity. The code to parse a Candidate Puppet statement might be several magnitudes larger but I won’t know how much until I’ve done some additional work.

Posted in Side Projects | Tagged | Leave a comment

iPhone Screen Mockups

Some quick iPhone mockups. Some redesign is definitely in the works since the smaller screen sizes will affect visibility and gameplay. This is just a first pass.

campaign-puppets-iphone-horiz-1

campaign-puppets-iphone-vert-1

Posted in Side Projects | Tagged | Leave a comment

Campaign Puppets

Over the years I’ve played many computer games about US presidential elections, games like Doonesbury Election Game: Campaign ’96The Political Machine, and President Forever. They were entertaining but ultimately degenerated into a state-by-state resource grind. In 2012 I started development on an iOS game focused on the Republican primary elections but I wasn’t able to come up with a design that satisfied me.

On November 26th I watched my first Republican debate of the 2016 primary season and I was appalled at what I saw. I’ve heard about the tenor and tone of the prior debates but I didn’t believe it had reached this level until I saw it with my own eyes. The candidate interactions were anything but presidential, the moderator couldn’t stop the candidates from abusing the format (I don’t know why they don’t turn off their mikes when they go over their time limits), and the whole event made me sad about the direction our political process is heading (I fear the movie Idiocracy is strangely prophetic).

But the whole event did give me an idea for a US presidential election primary computer game for smartphones and tablets that might tap into today’s political zeitgeist, be somewhat entertaining, and let me expand on some ideas I first implemented in Teen Talk. The goal of the game is to win your party’s nomination in a series of debates. The topic is US politics. The gameplay should reflect the conditions of a real debate where one misstatement can bring you down in the polls.

The entire game is played on one screen (see my Entire Game on One Screen post for why I’m going with this design).

campaign-puppets-screen-1

On the right side are the candidates (A); on the left are the topics they’ll be questioned about (B). The topic list is scrollable since their will be more topics than can be displayed in the available area (same for the candidate list if necessary).

At the top are the panel of reporters who’ll be asking the candidates questions (C). The reporter’s questions and candidate answers appear in the conversation area (D) and scroll off the top of the screen as time goes by (you can scroll up to see previous dialog).

Candidate replies and interjections are created using the iconic inverse parser (E) at the bottom of the screen along with the candidate and topic icons.

campaign-puppets-screen-1-annotated

Reporter’s questions are asked in iconic statements. The mockup question below uses, from left to right, top to bottom, the following icons – Trump Iran Favor/Agree Strong Attack/Offense Smart Nuclear QuestionMark (these are not final, just a quick mockup).

In the player’s mind my hope is that it translates into something like the English equivalent of “Mr Trump on Iran you favor a strong offense but is that smart given Iran’s nuclear program?”

question-trump-1

The player replies using the inverse parser at the bottom of the screen as well as the candidate and topic icons. They could have the candidate say

trump-reply-1

or

trump-reply-2

or even

trump-reply-3

These are not the exact icons and statements that you’ll be able to create using the game’s rhetoric engine, just something I threw together using icons from The Noun Project. Also, the statements you can create might be a combination of icons, words, and interactive modifiers to indicate intensity and tone.

Some other gameplay elements that could be programmed in add a tag team wrestling flavor to the debate:

  • Your replies could be time dependent, you only have so much time to respond and any hesitation gives another candidate the opportunity to interrupt or sandbag you
  • Other candidates could interrupt you if your attacking them in their response (a candidate’s inclination to attack would be based on their individual personality traits).
  • Candidate ranking top-to-bottom could change to reflect public perception of who’s “winning” the current debate.
  • Changes in individual candidate traits could be displayed next to a candidate’s icon to give you realtime feedback on how your attacks against them are doing.
  • Candidate traits could be tied to realtime facial animation on candidate icons (examples here and here).

I’m going to give this some additional thought over the next couple of days, particularly while watching the next Republican debate on March 3rd.

Posted in Side Projects | Tagged | 1 Comment

Where’s George Modified Design

 

Here’s the original design for Where’s George

WheresGeorgeAppMockup

I’ve decided to modify the design to allow the app to handle more than one pet. The background color indicate a pet’s location (in the mockups below, green indicates outside while blue indicates inside).

Swiping a pet line item to the left displays the valid action you can take on that particular pet–if they’re outside the house coming in you can only select Out; if they’re outside coming back inside you can only select In.

George-01

To add a new pet you select the plus sign in the upper right. On the Pet Details screen you add a picture by tapping the square and type your pet’s name in the field below.

George-02

To delete a pet from the list you swipe to the right and tap the trash can (this left/right swipe control isn’t out-of-the-box Xamarin Forms so I’ll have to look into creating something).

Posted in Side Projects, Software Development | Tagged , , | Leave a comment

OnBelay Game Pieces

Some 3D printed pieces for a rock climbing game prototype I’m working on.

CZFCrU5UkAE9-HS

FullSizeRender

IMG_1789

Posted in Other, Side Projects | Tagged , | Leave a comment

Viand Sync Diary #4 – More Notes

Some quick notes  that I jotted down about syncing a single database between two app instances.

Each app’s database will have a unique ID

  • Generated at app startup if it doesn’t already exist
  • Where stored?

App Functions

  • Create Account – email, password
  • Sign In to Existing Account – email, password
    • Azure Accounts table – email, password (hashed), database ID

@1, pwd 1, ID A
@2, pwd 2, ID B

  • Share List
App Azure
@1 creates account @1 ID A
@2 creates account @1 ID A
@2 ID B
@1 shares ID A with @2 (needs @2) @1 ID A
@2 ID A
Database associated with @2 changed if @2 found

Need to flesh all this out more.

Posted in Side Projects | Tagged , , | 1 Comment