Elm Workshop: Day Two

Day Two!

  • Richard start off with some Q&A, and we got some site recommendation when someone asked about learning tools. Although it was only a day (albeit an 8 hour day…), I got enough info that I can imagine applying it to one of my idea for a side project, but I definitely need some information to actually implement it.  I particularly like the article Building a Live-Validated Signup Form in Elm by noredink. Richard is also in the process of writing a book, Elm in Action, to be publishing by Manning. He also mentioned Egghead.io as a possibility, though he haven’t tried it himself. If I remember correctly, it is a paid subscription service, so I will probably try the noredink articles first.
  • Triple Quotes (“””): multiline string
  • Decoder Integer: Decoder check a JSON string and returns a “Result”, which should hold “Ok” if the decoding process is run smoothly (it can be decoded into a integer), “Err” if not.
  • decodeString is a shorthead for Json.Decode.decodeString after importing with the command import Json.decode exposing (..). Much better when you are doing a bunch of decodeString.
  • Int is a decoder. List is a function that takes in a decoder such as an Int, and returns another decoder.
  • Shelf (at [“name”] string) <— Find value at list key name, which should return a string to function named Shelf. The list key is in square bracket because it can hold nested keys.
  • Decoder
    • decode User
    • |> require “id” int <— Need to be id holding int
    • |> option “name” string “(falllback)” <— optional. If key not there, use the value in fallback.
    • |> hardcoded 1.0
  • Side Effect: unlike JS, Elm don’t have side effects.
    • Instead, it have Manage Effect.
  • GetString: takes in String, returns Task Error String <—The Error holds a Network HTTP error. UnexpectedPayLoad gets return if JSON decode fails. Task is like a to-do list – list by don’t do. Notes that this doesn’t invoke network traffic – GetString is a Task.
  • andThen and sequence: takes a Task and chain to others, building a full Task.
    • Some task cannot be chain together. Ex: random number generator.
  • Command messages (type Cmd) do not have error handling, unlike Tasks (type Task). Tasks is very general.
    • HandleSearchResponse(List SearchResult) and HandleSearchError Http.Error are both functions that returns Cmd.
  • Let … in expression: intermittent value (like variable) are defined with tasks (like value). No outside scoop outside see the value, until the code reach in, where the in scoop can call anything in the let scoop.
  • Maybe: in Elm, there is no undefined or null, it have a Maybe type container, and the type returns a “Nothing | Just a”. (Indecisive little guy, isn’t it?)
    • Attendee asked “Why Maybe exist?”. Answer was that it was to prevent error.
    • Just precedes a value to apply a wrapper.
  • Access JavaScript by sending to its port
  • Subscription is synchronize.
  • Elm packages
    • dependencies: used github repo.
    • elm is very strict on having the latest version. Reject if its old
    • testing project: project-fuzzball ????
  • Expect.equal compares 2 values for equals.
  • Left pipe ( <| ): calls a function. Eliminates parentheses. foo (bar baz) in JS is foo <| boo baz in Elm.
  • Unit ( () ): seriously is just a parentheses. Indicates that there is nothing happening. Tells function that it pass to that nothing is being done. Delays evaluations of test.
  • Fuzz Testing: do a test multiple times with randomly generated input.
  • Shrinking: when encounter error, the program tries to find something small and minimal to present to coder for debugger. Thank you Elm!
  • Set: a set of unique values. Get rids of duplicates.
    • Set.member will find out if the arg exist in the list
    • Set.insert – obviously, insert value.
  • Dict: dictionary of keys and values (Richard jokes “Careful how you pronunciation that.” Indeed, indeed…)
    • Key type and value type must be consistent throughout the dict.
    • .get returns Maybe types, meaning a Nothing or Just.
    • Maybe.withDefault { —Fallback Json } (Dict.get “key” DictName) <—This give a fallback value when the key is not found in the Dict list named DictName.
  • result -> result.id can be shortened to {id} ->
  • { model | results = resultsById } ! [] is equal to { model | results = resultsById } ! command.none
  • Compose ( >> ): sibling to pipe (|>). Do one action to another item. The arrow can go either way.
  • React all about component. Elm uses component only when needed because it keeps simplicity, but takes more effort when encapsulation is needed.
  • Further Studies: Look up tail-recursion for fast performance optimization. Html.Lazy is another one good for performance optimization.

Elm Workshop: Day One

Braving the Pride Weekend commuter traffic, I just attended day one of Elm Workshop, presented by Richard Feldman from NoRedInk, hosted by Women Who Code, and located at Pivotal Lab (yep, a lot of people went into this). Learning a functional programming language for the first time is a truly fascinating experience, especially if one does in 8 hours straight! Most of what I learned are from the in-workshop exercise, but here are some notes for day one. Note that this is from a very compacted 8 hours course, so I can only hope I didn’t misunderstand something:

  • Compared Babel to Elm: both translates languages
  • if-else is a statement in JavaScript, but expression in Elm. The last line in a function is a return value.
  • Uses then instead of {}.
  • Arguments are separated by space.
  • Only have double equal (==). No triple equal (===). Slash equal (/=) instead of bang equal (!=).
  • When calling functions, space are used instead of parentheses. Parentheses are used for grouping, not indicating function call.
    • instead of text( pluralize (“self”, “shelves”, 5)), do text (pluralize “self” “shelves” 5)
    • in the above sample, parentheses are used to ensure the result of function pluralize is passed as argument for function text, not all 4 item (function pluralize, string “self” and “shelves”, and integer 5).
  • Elm is not good with tab – change to space.
  • String are always double quotes.
  • Pro: good in debugging. When compile, error message occurs and points developer to where the problem is.
  • Single plus (+) in Elm is resolve for arithmetic. For concatenation, double plus (++) is used.
  • For HTML output, square brackets are used for each tag, in general. Text are precedent by text. Comma help separates. For HTML output, the functions – named as HTML tags such as div – takes 2 argument: list of attributes and list of children.
    • Comma is placed at the beginning of a statement instead of end. That’s a convention in Elm to make sure commas are not forgotten.
  • List: all elements in list for Elm must be the same type of value, unlike JS.
  • Type Indication: To declare the value of a variable, add : Type Type-of-type, such as apple: List String or shelves: Html a
    • Empty list type is undefined. Calling it in various name will work. If the first type is undefined, a can be places.
    • Type indication can also indicate the return type with an arrow, such as pluralHtml : number -> Html a (Format: function: type-it-takes -> type it returns).
  • Partial Application: When a function only give partial information regarding the argument for another function.
  • List.map(: grabs the list, runs though the list and apply something.
  • Anonymous function are defined by slash ():
    • List.map(function(shelf) { return viewShelf(shelf); })
    • (List.map (shelf -> viewShelf shelf) shelves)
    • Ext-function(anoy-function-arg -> return-function/value), Ext-function-arg2
    • But we can also pass the function directly in cases where it is just a function being passed to another function.
    • List.map viewShelf shelves
  • Interactive:
    • onClick{} instead of Eventhandler
    • Msg instead of Callback
  • True/False is capitalized in Elm because it is a uni-type in Elm, unlike JavaScript which is all lowercase.
  • Record and UniType
    • Records data are called use using dot (.): model.data
    • UniType are called using case:
      • case arg of
        • uni-type-class1 uni-typevalue1-> { function or changes }
        • un-itype-class1 uni-typevalue1 -> { function or changes }
  • Debug.log: wrap it around what you want to log. Acts like console.log.
  • For imports, exposing(..) means bring everything in.
  • Pipeline Encoding: [ “list”, “items ] |> variableType.function1 /> variableType.function2  <= runs multiple function with a set of argument. ( Example: [“apple”, “orange”] /> List.reverse /> List.map String.toUpper means List.map String.toUpper(List.reverse [“apple”, “orange”]). )
  • Type Alias can take in arguments and return a record if the type alias has the variable defined by type only (the variable is not assigned values or expression)