Posted by Gizra on Wed, 12/30/2015 - 00:00

In August 2015 I challenged myself (and later the rest of the Gizra devs) to create a typical web-app with all the bells and whistles in Elm. It's called elm-hedley, and I'm super proud it is now featuring in Elm's front page.

This post is going to give a high level overview and point out some parts that are worth noting. However, before diving into the technical section, it is important to emphasize the virtues of simply doing.

If you would go back in the commits history you would see some nasty stuff that have been completely overhauled and polished. The only way of getting to that "improving" part is of course by starting! Only after that will one become smarter and recognize what needs improving, as well as be more experienced to know how to do it.

Continue reading…

Posted by Rundis on Mon, 12/28/2015 - 01:00

Join me on my journey into statically typed functional languages. I’ve been living a pretty happily
dynamic life so far. What’s the fuzz with all those types ? What do they give me in a real life
scenario (aka is it worth using for work gigs) ? I need to make an effort and try to figure
some of this out. This blog series is an attempt to document some of my experiences along the way through a practical example.

There will be:

  • A single page web application with crud features
  • Lots of types, refactoring and hopefully some testing
  • An evolving web-app github repo for your amusement or amazement

Just a little background on me

For quite some time I’ve been wanting to learn more about functional languages that are statically (and strongly) typed.
What benefits do they really provide in practice and what are the downsides ?
My background is a from quite a few years with Java, and the last 3-4 years I’ve been working
mostly with Groovy, JavaScript and Clojure/ClojureScript.
I’ve dabbled a little with Elm recently (minesweeper in Elm)
, and I’ve tried to take on Haskell a couple of times (without much success I might add).

I mostly do web apps at work, so I figured I need to try and make something at least remotely
similar to what I do in real life.

Let’s get started

This is the point where I’ve run into analysis paralysis so many a time before.
So I set out to create a crud app, but what shall I build. After some deliberation
I settled on making something related to Music. You know Albums, Artists, Tracks and such.
I have no idea what the end result will be, but to start off I’ll make a simple spike.

artists

The spike should

  • establish a base architecture
  • implement a simple feature: List artists

You will find the sample application code on github.
There will be a tag for each blog post in the series

Backend

I wanted to implement server component that would provide REST-services. There are quite
a few options available for Haskell that can help with that. After some research and trials
I ended up using Servant.

Some of the other options I looked at includes:

I just had to choose one, and Servant seemed like a nice fit for REST stuff and I managed to get it
working without to much hazzle.

Project set up

I’m using cabal, but you might also want to consider looking
at stack.

name: albums
version: 0.1.0.0
synopsis: Albums rest backend
license: MIT
license-file: LICENSE
author: rundis
maintainer: mrundberget@hotmail.com
category: Web
build-type: Simple
cabal-version: >=1.10

executable albums
main-is: Main.hs (1)
build-depends:
base >= 4.7 && < 5
, either
, aeson >= 0.8 (2)
, servant (3)
, servant-server
, wai
, warp
hs-source-dirs: src (4)
default-language: Haskell2010

1
The entry point for the application

2
Provides JSON support

3
The servant library that helps us create type safe rest services

4
The directory(ies) where the source code for our app resides

For the purposes of this spike all haskell code will reside in Main.hs. This will
surely not be the case as the app progresses.

If you wan’t to try out automatic reloading support, you may want to check out halive.
Unfortunately I couldn’t get it to work on my machine (OS/X Maverick), but it might work our for you though :-)

Main.hs

data Artist = Artist
{ artistId :: Int
, name :: String
} deriving (Eq, Show, Generic)

A simple type describing the shape of an Artist in our app.

instance ToJSON Artist (1)

type ArtistAPI = (2)
Get '[JSON] [Artist] (3)
:<|> Capture "artistId" Int :> Get '[JSON] Artist (4)

artistsServer :: Server ArtistAPI
artistsServer = getArtists :<|> artistOperations (5)

where getArtists :: EitherT ServantErr IO [Artist]
getArtists = return artists (6)

artistOperations artistId =
viewArtist

where viewArtist :: EitherT ServantErr IO Artist
viewArtist = artistById artistId (7)

1
ToJSON is a type class. This line
basically is all we need to set up for json encoding an instance of our Artist type.

2
We describe our REST api using a type

3
Get on this api returns a list of Artists

4
Definition of how to get a single Artist by it’s id

5
The server type is the part where we descibe how we actually serve the api

6
The handler for listing artists. Currently it just returns a static list

7
The handler for retrieving a given artist by its id

:<> is a combinator that ships with Servant. It allows us to combine the various parts
of our API into a single type.

artistById :: Int -> EitherT ServantErr IO Artist
artistById idParam =
case a of
Nothing -> left (err404 {errBody = "No artist with given id exists"}) (1)
Just b -> return b (2)
where
a = find ((== idParam) . artistId) artists (3)

1
If the find (by id) in 3 returns Nothing (see Maybe monad).
We return a 404 error with a custom body

2
Upon success return the given artist instance

3
Find a given artist by id from our List of artists

EitherT - An either monad. Check out the description from the servant tutorial on EitherT

Wrapping it all up

type API = "artists" :> ArtistAPI (1)

api :: Proxy API
api = Proxy (2)

app :: Application
app = serve api artistsServer (3)

main :: IO ()
main = run 8081 app (4)

1
A generic type for our api. It let’s us combine multiple types, but the
main reason it’s factored out for now is to avoid repetion of the root path for our
api artists

2
TBH I haven’t grokked why this is needed, but it’s probably to do with some type magic ?

3
An "abstract" web application. serve gives us a WAI web application.
I guess WAI is like a common API for Haskell Web applicaitons.

4
The main entry point for our application. It starts our web application on port 8081
(and uses warp behind the scene to do so.)

To get the backend up and running, check out the readme for the sample application

Backend experiences

Following the Servant tutorial it was quite
easy to get a simple translated example to work. However I did start to struggle once I started
to venture off from the tutorial. Some of it is obviously due to my nearly non-existing haskell knowledge.
But I think what tripped me up most was the EitherT monad. Heck I still don’t really know what
a monad is. The error messages I got along the way didn’t help me much, but I guess gradually
they’ll make more and more sense, once my haskell foo improves.

Frontend

So Elm is pretty cool. The syntax isn’t too far off from Haskell. I’ve already started
looking at Elm so it makes sense continuing with Elm to hopefully gain deeper knowledge of its
strenghts and weaknesses.

For a really pleasurable experience when developing elm I would suggest choosing an
editor with linting support. As a shameless plug, one suggestion would be to use Light Table
with my elm-light plugin. (Emacs, Vim, Sublime, Visual Code are other good options)

Project setup

{
"version": "1.0.0",
"summary": "The frontend for the Albums CRUD sample app",
"repository": "https://github.com/rundis/albums.git",
"license": "MIT",
"source-directories": [
"." (1)
],
"exposed-modules": [],
"dependencies": { (2)
"elm-lang/core": "3.0.0 <= v < 4.0.0",
"evancz/elm-effects": "2.0.1 <= v < 3.0.0",
"evancz/elm-html": "4.0.2 <= v < 5.0.0",
"evancz/elm-http": "3.0.0 <= v < 4.0.0",
"evancz/start-app": "2.0.2 <= v < 3.0.0"
},
"elm-version": "0.16.0 <= v < 0.17.0"
}

1
For simplicity source files currently resides in the root folder of the project.
This will change once the application grows

2
Initial set of dependencies used

Album.elm

Before you start you may want to check out start-app.
The frontend code is based on this.

type alias Artist = (1)
{ id : Int
, name : String
}

type alias Model = (2)
{ artists : List Artist}

type Action = ArtistRetrieved (Maybe (List Artist)) (3)

1
Front end representation of Artist. You’ll notice it’s strikingly similar
to it’s Haskell counterpart on the server side

2
Type for keeping track of our model. Currently it will only contain
a list of artists, but there is more to come later

3
"Tagged type" that describes the actions supported in the frontend app.

init : (Model, Effects Action)
init = (1)
( Model []
, getArtists
)

update : Action -> Model -> (Model, Effects Action)
update action model = (2)
case action of
ArtistRetrieved xs ->
( {model | artists = (Maybe.withDefault [] xs) }
, Effects.none
)

getArtists : Effects.Effects Action
getArtists = (3)
Http.get artists "http://localhost:8081/artists"
|> Task.toMaybe
|> Task.map ArtistRetrieved
|> Effects.task

artist : Json.Decoder Artist
artist = (4)
Json.object2 Artist
("artistId" := Json.int)
("name" := Json.string)

artists : Json.Decoder (List Artist)
artists = (5)
Json.list artist

1
Initializer function called by start-app when staring the application
it returns an empty model and an effect getArtists. Meaning getArtists will be
invoked once the page is loaded

2
The update function handles actions in our app. Currently it only supports
one action, and that is the a callback once getArtists have returned. It updates
the model with the retrieved artists and returns the updated model

3
Our ajax call ! We invoke the our rest endpoint using the elm http library. The first
argument to Http.get, artists, tells elm how to decode the result.
A lot is going on here, but the end result is that it does an xhr request decodes the result (if success)
using the given decoder and eventually invoke the update function with our list of artists (wrapped in a Maybe).

4
A decoder for decoding the json representation of an artist from the server to and Artist type instance

5
The response from our rest endpoint is a list of artists, so we use the JSON.list function
telling it to use our artist decoder for each item in the list

artistRow : Artist -> Html
artistRow artist = (1)
tr [] [
td [] [text (toString artist.id)]
,td [] [text artist.name]
]

view : Signal.Address Action -> Model -> Html
view address model = (2)
div [class "container-fluid"] [
h1 [] [text "Artists" ]
, table [class "table table-striped"] [
thead [] [
tr [] [
th [] [text "Id"]
,th [] [text "Name"]
]
]
, tbody [] (List.map artistRow model.artists)
]
]

1
Function to generate the view for a single artist row

2
Our main view function for presenting a list of artists

We are not rendering dom nodes here, it’s just a representation of what we want
to render. The actual rendering uses Virual DOM.

Wrapping up the frontend

app : StartApp.App Model
app = (1)
StartApp.start
{ init = init
, update = update
, view = view
, inputs = []
}

main : Signal Html
main = (2)
app.html

port tasks : Signal (Task.Task Never ())
port tasks = (3)
app.tasks

1
Using startapp to wire up our core functions (init, update and view)

2
The entry point function for our frontend app

3
When communicating with the outside world elm uses ports.
This is used for by our rest invocation. It does so using tasks which
is the elm way to describe asynchronous operations.

Frontend experiences

Elm ports, tasks and effects are concepts that are yet to dawn completely on me. I protect my brain
temporarily by giving them overy simplistic explanations.
I wasn’t sure how to do the JSON decoding stuff, but fired up an elm-repl in Light Table and just experiemented a little until
I had something workable.
I used the linter feature of my Light Table plugin quite heavily, and the error messages from elm proved yet again
to be very helpful.

Conclusion and next steps

I pretty sure I could have knocked this up with Clojure/ClojureScript, groovy/grails or plan old JavaScript
in a fraction of the time I’ve used. But that’s not really a fair or relevant comparison.
Learning completely new languages and new libraries takes time.
I think I’ve learned quite a bit already and I’m very pleased to have made it this far !

Elm was easier to get into than Haskell and the Elm compiler felt a lot more helpful to me than
ghc (haskell compiler). I had a head start on Elm, but I do remember getting started with Elm felt
a lot smoother than jumping into Haskell. I’m still very much looking forward to improving my haskell skills
and I’m sure that will proove very valuable eventually.

So what’s up next? Not sure, but i think adding persistence and the facility to add/update
artists might be next up. I will keep you posted !

Posted by codecentric on Fri, 12/18/2015 - 18:39

Nearly all modules you’ll write in Elm need to import other modules to do their work; also, all our examples so far had some import statements. In this episode, we take a closer look at the import statement and at the different ways to import modules.

About This Series
This is the eighth post in a series of short and sweet blog posts about Elm. The stated goal of this series is to take you from “completely clueless about Elm” to “chief Elm guru”, step by step. If you have missed the previous episodes, you might want to check out the table of contents.
Qualified Imports
Let’s look at a basic example that just renders some static HTML:
import Html
import Html.Attributes

main : Html.Html
main =
Html.div []
[ Html.p [] [ Html.text "This is the first paragraph" ]
, Html.p [] [ Html.text "This is another paragraph" ]
, Html.hr [] []
, Html.ul []
[ Html.li [] [ Html.text "some" ]
, Html.li [] [ Html.text "bullet" ]
, Html.li [] [ Html.text "points" ]
]
, Html.p []
[ Html.text "This is the "
, Html.span
[ Html.Attributes.style [("font-weight", "bold")] ]
[ Html.text "closing"
]
, Html.text " paragraph."
]
]
This would render the following HTML:
<div>
<p>This is the first paragraph</p>
<p>This is another paragraph</p>
<hr>
<ul>
<li>some</li>
<li>bullet</li>
<li>points</li>
</ul>
<p>
This is the <span style="font-weight: bold;">closing</span> paragraph.
</p>
</div>
As always, go ahead and try stuff out for yourself, for example by copying this into a file named Imports.elm and check the result with elm-reactor.
This piece of Elm imports two modules, Html and Html.Attributes:

import Html
import Html.Attributes

An import statement basically tells the Elm compiler to load these two modules and to use stuff from them whenever it encounters anything that is prefixed with Html. (or Html.Attributes., respectively). Thus, we know that the functions Html.text or Html.Attributes.style that we are using in the example code come from said modules.
By the way, where do the imported modules come from? That depends. You can import modules from third party packages that have been installed via elm-package install. You can also import your own modules from your current project’s source folder (there will be a separate blog post on how to structure your code base with modules later).
In this example, we are importing modules from the package evancz/elm-html so you would need to install this via elm-package install --yes evancz/elm-html to follow along. If you already did the examples in episode 3 or episode 4 you can just create a new file (say, Imports.elm) in the same elm-playground directory and you are good to go. We already installed the elm-html package there.
Coming back to the example code, let’s be honest here: This code looks really bloated with all the redundant Html.qualifiers. This is where the exposing keyword comes in.
Open Imports aka Unqualified Imports
The following code example makes use of open imports by using import exposing, so that the imported identifiers can be used without prefix.

import Html exposing (Html, div, hr, li, p, span, text, ul)
import Html.Attributes exposing (style)

main : Html
main =
div []
[ p [] [ text "This is the first paragraph" ]
, p [] [ text "This is another paragraph" ]
, hr [] []
, ul []
[ li [] [ text "some" ]
, li [] [ text "bullet" ]
, li [] [ text "points" ]
]
, p []
[ text "This is the "
, span
[ style [("font-weight", "bold")] ]
[ text "closing"
]
, text " paragraph."
]
]

The first difference I would like to draw your attention to is in the import statement section:

import Html
import Html.Attributes

versus

import Html exposing (Html, div, hr, li, p, span, text, ul)
import Html.Attributes exposing (style)

By appending exposing to the import statement we can specify a list of identifiers that can be used unqualified (that is, without the module name as a prefix) in our module. That’s the reason why we can drop all the Html. prefixes in the main function. Html.text becomes just text, Html.p becomes p, and so on.
Another detail is that this does not only apply to functions but to all identifiers that a modules exports. In particular, it also applies to types. The type annotation in the first example had to be written as

main : Html.Html

This is because the name of the module that we import is Html and the name of the type that this module exports is also Html. Thus, the full qualified name of that type is Html.Html.
In the second example we added the name of the type to the list of identifiers to be exposed for unqualified usage – if you look close enough, you can spot the Html in the exposing clause for the Html import. With that, the type annotation in the second example can be written as

main : Html

Expose Everything
The second example already looks a bit cleaner. However, as soon as you start to use more and more HTML tags (or, functions from the Html module, that is) you always need to add them to the exposing part of the import. This can be a bit annoying. Elm has a special import syntax to avoid this.

import Html exposing (..)
import Html.Attributes exposing (..)

-- main function is the same as in the second example

With import Html exposing (..) we tell the Elm compiler to expose every identifier the Html module has to offer and we can use them all in their unqualified form.
Import Aliases
Another feature of the import statement is that you can alias the imported module.
Say, you would not want to import unqualified from Html.Attributes, for whatever reason. You would have to prefix the styles function call with Html.Attributes again, as in our first example. Html.Attributes.styles is pretty long though. What you can do is define an alias for that:

import Html.Attributes as Attr
Html.Attributes by prefixing them with Attr, like this:

Attr.style [("font-weight", "bold")]

You can also combine aliases and exposing. This might make sense if you only expose a few of the imported identifiers but still want a shorthand notation for the qualified usages.

import Html as H exposing (Html)

main : Html
main =
H.div [] [ H.text "whatever" ]

Here, we only expose the type Html for unqualified usage (thus, we can write the type annotation as main : Html instead of main : Html.Html) but alias the module name Html as H and use this alias to refer to the functions from Html. (Note: I do not recommend this approach, see below for some recommended best practices regarding imports.)
Default Imports
A small number of modules are imported into every module by default, even if you do not have explicit import statements for them. Here is the set of default imports (for Elm 0.16):

import Basics exposing (..)
import Debug
import List exposing ( List, (::) )
import Maybe exposing ( Maybe( Just, Nothing ) )
import Result exposing ( Result( Ok, Err ) )
import Signal exposing ( Signal )

This means that, for example, you can use every function from the Basics module, without prefixing them.
There are two things that might need a little explaining with these import statements.
First, the import statement for List exposes ( List, (::) ): The module List has a type named List that gets exposed. This is pretty straight forward and we have already seen this with the Html module. But what is this (::) about that also gets exposed? Function names in Elm usually use alphanumeric characters, but you can also use identifiers that only use non-alphanumeric characters (:, |, <, $, ...), you just need to wrap those names in parantheses in the function definition and when importing them. As you might recall from our last episode, :: is the append operator for lists. It is actually not something special build into the Elm compiler but just a regular function definition on the List module. We can use the function (::) everywhere because it is imported and exposed by default. Also, you can always use functions like this without the parantheses as infix operators. That's the reason why you can write [1, 2] :: [3, 4] in Elm without importing anything explicitly. You can also define your own infix operators that way.
Second, the exposing clauses for the Maybe and Result imports use syntax we have not covered yet. The module Maybe exports a union type named Maybe. We did not talk about union types yet. For now, it suffices to say that a union type is just an enumeration of type values. Here is the definition of the Maybe type:

type Maybe a = Just a | Nothing

So a value of type Maybe can either be Nothing or Just a for some other type a.
The import statement import Maybe exposing ( Maybe( Just, Nothing ) ) makes the two individual values from the union type (Just and Nothing) available to our code.
Best Practices for Import Statements
Now that we have completed our short tour of import statements in Elm, it is time to talk about some recommendations regarding code style.
The following are my personal preferences, you are welcome to come up with your own.

  1. Use qualified imports as much as possible. That is, prefer import Array over import Array exposing (..). This makes your code a bit more verbose, but it is immediately obvious where an identifier comes from.
  2. Use exposing (..) only for a few selected modules. Actually, I tend to only use it for Html, Html.Attributes and Html.Events at all, nothing else.
  3. Expose types that have the same name as their module. That is, for a (fictional) module named LinkedList, that also exports a type LinkedList, use import LinkedList exposing (LinkedList). This way, you can use the type in type annotations like someFunction : LinkedList instead of writing someFunction : LinkedList.LinkedList.
  4. Do not use aliases (import Something as Sth) to shorten module names. In my opinion the savings in characters it is not worth the additional cognitive load, especially when modules are aliased differently all over your code base.
  5. Do use aliases for multi-segment module names and use the last segment as the alias. Example: import Some.Thing.MyModule as MyModule.

A Word About Writing HTML in Elm
This episode is about import statements but somehow we also briefly touched the topic of how to produce HTML in a readable fashion. The third example given above (using import Html exposing (..) is okay-ish, but probably not the best we can do.
If you are used to templating languages, you might not like how that looks in Elm. There is a very good discussion about that on the elm-discuss mailing list. Go read it if you are interested in patterns to do this in a nice way. In particular, this answer seems to get it quite right from my point of view.
Last but not least, the modules elm-html-shorthand and elm-bootstrap-html might come in handy for this.
Remarks About Pre-0.15 Syntax
Elm is still relatively young and the syntax has changed a few times with the latest versions. The syntax will probably stay much more stable with the 1.0 release. There are still a lot of examples out there using older syntax. With regard to imports, version 0.15 brought some important changes, introducing the exposing keyword.
You might stumble over examples using the old syntax without the exposing syntax, like this:

import Html (..)
import Html.Attributes (style)

For this, just insert exposing between the module name and the list of exposed identifiers.
With this we conclude the eighth episode of this blog post series on Elm. Stay tuned for the next episode. See you next time!
The post Elm Friday: Imports (Part VIII) appeared first on codecentric Blog.

Posted by LambdaCat on Tue, 12/15/2015 - 15:30

I recently decided to retrain myself as a terminal Emacs user (I'm nostalgic for the '80s and my old glorious green and black terminal :P)

So I switched all my Elm editing from Sublime Text (which works and is pretty nice) to Emacs (which also works and is pretty nice)

Posted by codecentric on Fri, 12/04/2015 - 23:45

Lists are one of the core data structures in Elm. Elm supports lists on the syntactical level and the List core module has the usual basic utilities you would expect from a functional language. In this post, we take a look at lists in general and some of the useful functions from that module.

About This Series
This is the seventh post in a series of short and sweet blog posts about Elm. The stated goal of this series is to take you from “completely clueless about Elm” to “chief Elm guru”, step by step. If you have missed the previous episodes, you might want to check out the table of contents.
Prelude: elm-repl
A great way to follow along and immediately try the code of this episode (instead of just reading it, which would probably be quite boring) is Elm’s REPL (read-eval-print-loop). With Elm installed, just start elm-repl in the command line. You should see something like this:

>elm-repl
---- elm repl 0.16.0 -----------------------------------------------------------
:help for help, :exit to exit, more at
--------------------------------------------------------------------------------

Now any Elm expression that you type will be evaluated immediately and the result is printed back to you. You probably wouldn’t want to develop anything complicated in the REPL but it’s great for playing around with some basic code snippets. So each time you see some code in this episode, try it out in the REPL and tinker with it. Have fun!
Creating Lists
There are a number of ways to create lists in Elm. The most straight forward thing is to simply write down the elements, comma separated, between square brackets:

aList = [1, 2, 3, 4]

Result:
[1,2,3,4] : List number

This looks a lot like arrays in C-Style programming languages, but Lists in Elm do not support positional access (you can not simply read/set the element at index n). Elm also has Array module, that offers positional access. But only lists are directly supported by syntactical elements so most of the times you’ll be working with lists.
As mentioned in the last episode, the actual type of a list always contains the type of its elements, that’s why the REPL infers the type List number here (you could also annotate this as List Intnumber is a supertype of Int).
Of course you can build lists from any type of values, not just primitives like Int, as long as all elements have the same type. Here’s a list of tuples for you:

[(1, 2, "three"), (4, 5, "six"), (7, 8, "nine")]

However, the following would raise a type error, because the second tuple has a different type than the first.

[(1, 2, "three"), (4, "five")]

Result:

-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm

The 1st and 2nd elements are different types of values.

3│ [(1, 2, "three"), (4, "five")]
^^^^^^^^^^^
The 1st element has this type:

( number, number', String )

But the 2nd is:

( number, String )

Hint: All elements should be the same type of value so that we can iterate
through the list without running into unexpected values.

When lists get longer you can and should split their definition over multiple lines. The style most people are used to (and which works fine in Elm) would probably look similar to this:

aList = [(1, 2, "three"),
(4, 5, "six"),
(7, 8, "nine")]

However, a lot of Elm code (including the code in Elm core and several community packages) use a different style where the comma is at the start of the line:

aList : List (number, number, String)
aList = [ (1, 2, "three")
, (4, 5, "six")
, (7, 8, "nine")
]

Of course, this is simply a matter of taste but it probably helps to have seen this style once so you know what’s up here.
(A remark for those of you who are following along with the REPL: Multiline expressions are possible in the REPL, though a bit of a hassle. End each line with a \ and start all lines except the first with a space. Or just skip the REPL tinkering for the multiline code snippets.)
Another way to create lists is the dot notation. The following snippet creates a list of Ints from 1 to 10.

[1..10]

Result:

[1,2,3,4,5,6,7,8,9,10] : List number

Last but not the least, in addition to the syntactical constructs to create lists you can also use functions from the List module. List.repeat takes an integer n and one arbitrary value and returns a list with n copies of this value.

List.repeat 4 "Elm"

Result:

"Elm","Elm","Elm","Elm"] : List String

List Manipulation
While this section is called “List Manipulation” you can not actually manipulate an existing list. In Elm, everything is immutable. The functions to manipulate a list all create a new list and leave the original list unchanged.
The prepend operator :: prepends an item to the start of the list:

1 :: [2, 3, 4]

Result:

[1,2,3,4] : List number

You can prepend multiple times in a row. Theoretically you could always start with an empty list and build your lists only by prepending elements:

1 :: 2 :: 3 :: 4 :: []

Result:

[1,2,3,4] : List number

There is no operator to add a single element to the end of a list. You can however, append a list to another list:

List.append [1, 2, 3] [4, 5]

Result:

[1,2,3,4,5] : List number

There is an infix operator ++ that is an alias for append:

[1, 2, 3] ++ [4, 5]

Result:

[1,2,3,4,5] : List number

So to add a single element to the end of a list you usually just wrap it in a list and use `append`/`++`. like this:

[1, 2, 3] ++ [4]

Result:

[1,2,3,4] : List number

Another way to build up a single list from smaller lists is the concat function which takes a list of lists and concatenates all of the individual lists into one large list:

List.concat [ ["one", "two", "three"], ["four", "five"], ["six"], ["seven", "eight", "nine"] ]

Result:

["one","two","three","four","five","six","seven","eight","nine"] : List String

Classics of Functional Programming
Now that we know a few different ways to build and manipulate lists, let’s have a look at some of the classical list functions that go beyond that.
Where would functional programming be without a map function? Of course the List module has one. List.map takes a function and a list and applies the function to all elements in the list. The result is a new list in which each element is the result of the function, applied to the respective element in the original list. Here is an example (please execute import String in the REPL before trying the example):

List.map ( word -> String.length word) ["a", "ab", "abc"]

Result:

[1,2,3] : List Int

In this example, we applied the length function to all elements in the list of strings.
List.filter is a similar evergreen. It takes a function and a list and removes all elements from the list for which the function returns False. The following snippet removes all negative numbers from the list.

List.filter ( n -> (n > 0)) [-1, 3, -2, 7]

Result:

[3,7] : List number

There are a lot more useful functions in the list module. Just to name a few:

  • List.head retrieves the first element of a list.
  • List.tail returns a new list where the first element has been dropped.
  • List.foldl and List.foldr reduce a list to a single element by combining the first two elements with a given function, then combining the result with the next element, and so on.

Best check the List module’s API docs what else it has to offer.
Finally, if the List module from core does not have what you need, check out the community package List.Extra for even more functional list goodness.
This concludes the seventh episode of this blog post series on Elm. Stay tuned for the next episode. See you next Friday!
The post Elm Friday: Lists (Part VII) appeared first on codecentric Blog.

Posted by codecentric on Fri, 11/27/2015 - 13:44

One of Elm’s most important characteristics is its static type system. This enables Elm to make much stronger guarantees during run time compared to dynamic languages like JavaScript. This boils down to “If it compiles, it’ll never throw a runtime exception”. In this episode, we’ll look into the type system and on type annotations in particular more closely.

About This Series
This is the sixth post in a series of short and sweet blog posts about Elm. The stated goal of this series is to take you from “completely clueless about Elm” to “chief Elm guru”, step by step. If you have missed the previous episodes, you might want to check out the table of contents.
Type Annotations Versus Type Inference
Although Elm is a statically typed language, our examples in the previous posts had no type declarations whatsoever. The reason is that Elm can infer the type of almost any expression. That means that everything is typed, either explicitly by adding a type annotation or implicitly by relying on Elm’s type inference.
Let’s revisit some of the functions from the last episode and add type annotations to them. The type annotations are the line just before the function definition:

import Html

multiply : number -> number -> number
multiply a b = a * b

square : number -> number
square a = multiply a a

productOfSquares : number -> number -> number
productOfSquares a b = multiply (square a) (square b)

incrementAll : List number -> List number
incrementAll list = List.map (\ n -> n + 1) list

incrementAll2 : List number -> List number
incrementAll2 = List.map (\ n -> n + 1)

main : Html.Html
main =
let
print n = Html.text <| toString n
in
Html.p []
[ print <| multiply 3 5
, Html.br [] []
, print <| square 4
, Html.br [] []
, print <| productOfSquares 2 3
, Html.br [] []
, print <| incrementAll [1, 2, 3]
, Html.br [] []
, print <| incrementAll2 [1, 2, 3]
]

(Remark: I refactored the main function a bit from the last episode by extracting the duplicated conversion from number/list into an HTML text element.)
To pick one example, square : number -> number is the type annotation for the function definition of square. A type annotation should be written directly in the line above the function definition. It is comprised of the function name, a colon, and the types of all input parameters and the return type, each separated by ->.
There is no distinction between a parameter type and the return type. Coming from other languages, you might expect that the type annotation for multiply somehow makes it clear that two numbers go in and one number comes out. For example the type signature could read (number, number) -> number. It doesn't. The separator between the first and second input parameter is ->, just as the separator between the second input parameter and the return type. This is because talking about first and second input parameter is just one way of thinking about multiply. You could also say that multiply takes only one parameter and returns a function with the signature number -> number. Both are equally valid points of view. You can either think of this function as (number, number) -> number or number -> (number -> number). The reason is that Elm supports currying and partial function application naturally.
Here is a code example that illustrates this:

import Html

multiply : number -> number -> number
multiply a b = a * b

multiplyByFive : number -> number
multiplyByFive = multiply 5

-- The expression (multiply 5) yields a new function with signature
-- (number -> number) by partial appication, that is: the first argument to
-- multiply is provided, but not the second.

main : Html.Html
main = multiplyByFive 3 |> toString |> Html.text

-- As you probably have guessed, the output of this snippet is 15.

Composing Types
Let's also have a look at the other two functions from the previous episode (and their type annotations):

incrementAll : List number -> List number
incrementAll list = List.map (\ n -> n + 1) list

incrementAll2 : List number -> List number
incrementAll2 = List.map (\ n -> n + 1)

These functions work with lists, but when talking about lists it is also important which type the elements in the list have. Therefore the full type here is not simply List but List number, that is, a list of number elements. This is just an example for the more general concept of parameterized types. This is mostly used in containers (like List or Maybe) and usually defines which type the contained elements have.
Generating Type Annotations Automatically
You can even let the Elm compiler tell you the type annotations. If you have Elm code without type annotations and you compile it with elm-make with the --warn flag, it will tell you all type annotations it inferred.
Going back to the example from the previous post (which had no type annotations), here's how that looks like:
elm-make --warn Functions.elm

=================================== WARNINGS ===================================

-- missing type annotation -------------------------------------- Functions.elm

Top-level value `multiply` does not have a type annotation.

3│ multiply a b = a * b
^^^^^^^^^^^^^^^^^^^^
I inferred the type annotation so you can copy it into your code:

multiply : number -> number -> number

Isn't that nice? I think it is.
Conclusion
Adding type annotations to your programs or omitting them is a matter of taste and style. However, the Elm style guide recommends having type annotations on all top level definitions. In my experience they often make it easier to solve compiler errors. And, to be quite honest, you'll do a fair share of fighting compiler errors when working with Elm. Therefore it usually pays off to add type annotations to your functions.
There is much more to Elm's type system then what have covered today -- union types, type aliases, type variables, tuples and records to name a few – but those will be topics for another Elm Friday.
This concludes the sixth episode of this blog post series on Elm. Stay tuned for the next episode. See you next Friday!
The post Elm Friday: Type Annotations (Part VI) appeared first on codecentric Blog.

Posted by crossingtheruby.com on Wed, 11/25/2015 - 02:00

My slightly obsessive endeavour of reading and doing everything stipulated on the official Elm Get Started page meant that after reading the Elm Complete Guide the Pragmatic Studio was up next. The guide was great, although a lot of the later stuff went over my head on first reading and I got the impression that a video course would be a useful way of tying together several loose threads in my quest to learn Elm.

Continue reading…

Posted by Gizra on Mon, 11/23/2015 - 00:00

planet.elm-lang.org is live!

Nice, right? Planet Elm and its RSS feed is up and running - just grab it, and the best Elm related posts would appear in your favorite RSS reader.

I felt the need for such a site the day I started with Elm. Getting the Gizra devs to build it was the next logical thing.

Having this main site as a central place for aggregating all the interesting content about Elm is yet another step in getting Elm into the mainstream.

If you maintain your own blog, go ahead, and submit your RSS feeds.

Continue reading…

Posted by FRONT END DEV THINGS on Sun, 11/22/2015 - 05:20

Quick follow up to my previous post, this assumes that you have set up your app and dev environment in the way I described.

1. Add a Component directory

mkdir src/Component

2. Create a component

touch src/Component/Hello.elm

3. Edit the component

Notice the magic namespacing here - our module name Component.Hello is derived from the name of the directory and filename.

// src/Component/Hello.elm
module Component.Hello where

import Html exposing (..)

sayHello : String -> Html
sayHello greeting =
div
[ ]
[ text (greeting ++ " from Hello component") ]

4. Import into Main.elm

Note: as Hello is simply an alias to Component.Hello which allows us to call its functions a little more concisely.

// src/Main.elm
module Main where

import Html exposing (..)
import Component.Hello as Hello

main =
Hello.sayHello "uhh... hi"

Posted by FRONT END DEV THINGS on Sun, 11/22/2015 - 02:11

It’s as easy as 1,2,… uhh.. 10

Our goal is to put together an Elm environment that includes custom HTML/SCSS and is suitable for a professional workflow for web applications.

The approach outlined here puts an emphasis on simplicity and minimal dependencies.

View the source code

Features of this environment

  • Customise your index.html (for including css/js etc)
  • Autocompile your Elm code on save (and view errors in IDE)
  • Autocompile your scss
  • Use elm-reactor as a local web server for development

Current limitations

This approach does not yet support use of the elm debugger. If that is unsuitable for you then I encourage you to print this post out and throw it in the trash.

OK, Let’s do this thing.

1. Install Atom IDE

Get the Atom installer here.

I chose Atom over Sublime Text (which is admittedly faster and more stable), Light Table, Microsoft VS Code because it currently has the best Elm language support and is easily extensible.

Maybe I’m backing the wrong horse here but so far Atom is working well for me.

2. Install these Atom packages:

These can also be installed from within Atom via Settings > Install

3. Install Elm on your computer

Get the Elm installer here.

Easy.

4. Create your application directory structure and core files

Type the following into your terminal (using Mac OSX - Windows is very similar. We’re just creating files and folders here)

mkdir MyApp
cd MyApp
mkdir src gen css
touch index.html src/Main.elm css/style.css save-commands.json
elm package install
elm package install evancz/elm-html

5. Configure save-commands to build your Elm files whenever you save them.

The elm make command is the officially supported build tool, so we can just automate that within our IDE instead of using a task runner like Grunt, Gulp, etc.

This part is a little tricky, as at the time of writing there are a couple bugs in this package that throw an error (details below). But it’s ok, we can get through this.

Open up the save-commands.json and enter the following in there.

// save-commands.json
{
"timeout": 5000,
"commands" : [
"src/**/*.elm : elm make src/Main.elm --output=gen/main.js"
]
}

Taking a look at that command in detail… the glob on the left of the colon tells save-commands when you want this command to run. Specifying src/**/*.elm means that it will be run only when we save a file within the src directory, or any of its subdirectories, as long as the file extension is .elm

The command itself is simply the manual elm make command you would use if you weren’t using elm-reactor, targeting only src/Main.elm and outputting it to gen/main.js. The reason we don’t want target all .elm files in the src subdirectory to build is because elm-make is designed to find and compile the necessary dependencies based on the import statements in your code.

Important note: you may get errors on save due to a couple bugs in save-commands. We’re gonna hack this ourselves today, but I expect these will be fixed in the future. Hopefully this will not be necessary in your case.

Commence the Hackery

  1. In Atom, Go to Settings and click the Open Config Folder button
  2. Find save-commands code under packages > save-commands
  3. Line 107 replace .find with .getElementsByClassName
  4. Save and test
  5. If you get an error about div.props not being a function just delete that line we ain’t got time for errors
  6. Be a good citizen and submit a pull request for your well-considered and careful changes.

tl;dr this will compile the Main.elm file (and all imported elm modules) to main.js and it will compile whenever you save any .elm file within src, or any of it’s subdirectories.

6. Set up your styles

This is going to look amazing.

//style.scss
body,
html {
font-family: "Comic Sans MS", cursive;
color: magenta;
}

When you save this file, sass-autocompile will produce a minified css file. Check out the docs to configure this as you like.

7. Set up Main.elm

This will be your app’s entry point.

// src/Main.elm
module Main where

import Html

main =
text "wow"

When you save this file save-commands will run elm-make on it, compiling all your Elm code into into gen/main.js.

8. Set up your html

// index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My App</title>
<link rel="stylesheet" href="css/style.min.css">
</head>
<body>
<script src="gen/main.js"></script>
<script>
Elm.fullscreen(Elm.Main);
</script>
</body>
</html>

Your app structure should now look like this:

MyApp
├─ css
│ ├─ style.min.css
│ └─ style.scss
├─ elm-stuff
│ └─ ...
├─ gen
│ └─ main.js
├─ src
│ └─ Main.elm
├─ elm-package.json
├─ index.html
└─ save-commands.json

9. Start your local webserver

Type this in the terminal from your app’s root directory.

elm reactor

10. Gaze upon the glory that is your new application

Point your browser to localhost:8000/index.html

To verify that your Elm code is compiling on save, edit your Main.elm file and hit save.

// src/Main.elm
module Main where

import Html

main =
text "much wow...?"

Refresh your browser (auto-refresh/hot-swap would be nice here instead…) and you should see your changes.

Also notice that since save-commands outputs the results of elm-make in a Elm compiler in an Atom pane you won’t need to keep switching to your terminal or browser to see compiler errors!

Next: organising Elm components

Posted by codecentric on Fri, 11/20/2015 - 16:35

Elm is a functional language, so naturally, functions and function calls are pretty import. We have already seen some functions in the previous episodes. This episode goes into more detail regarding function definition and function application.

About This Series
This is the fifth post in a series of short and sweet blog posts about Elm. The stated goal of this series is to take you from “completely clueless about Elm” to “chief Elm guru”, step by step. If you have missed the previous episodes, you might want to check out the table of contents.
Functions
This is a function definition in Elm:

multiply a b = a * b

The function definition starts with the name of the function, followed by the parameter list. As opposed to C-style languages like Java, JavaScript and the likes, there are no parentheses or commas involved, the parameters are only separated by spaces.
The equals character = separates the function name with the parameter list from the function body. The function body can be any Elm expression that produces a value. We can reference the parameters in the function body.
Function definitions can use other functions in their body. This is how this looks like:

square a = multiply a a

Here, we define a square function by using the multiply function we defined earlier. Function calls also don’t need any parentheses, just list the function parameters you want to pass into the function separated by whitespace.
You do need parentheses when you have nested expresssions:

productOfSquares a b = multiply (square a) (square b)

You can also declare anonymous functions (also known as lambda expressions) on the fly:

incrementAll list = List.map ( n -> n + 1) list

This thing wrapped in ( and ) is an anonymous function that takes one parameter and returns the parameter, incremented by one. This anonymous function is then applied to all elements in a list by using List.map.
Actually, we could have written this shorter. The following is equivalent:

incrementAll2 = List.map ( c -> c + 1)

Why is that the same? Because Elm supports something called currying. incrementAll defines a function that takes a list and produces another list. incrementAll2 also defines a function, but it is a function that takes no arguments and returns another function.
So when we write incrementAll2 [1, 2, 3] Elm first evaluates incrementAll2, gets a function and then procedes to put the remaining arguments ([1, 2, 3] in this case) into this function. The result is the same.
If you find it hard to wrap your head around currying, don’t worry about it too much for now. You can always resort to write a more verbose version of your function without currying and come back to this concept later. As a rule of thumb, if the last element in the parameter list in the function declaration is simply repeated at the end of the function body (like list in this case), you can probably omit both.
Let’s wrap this up. Here is a complete, working Elm program that uses the functions we defined above:

import Html

multiply a b = a * b

square a = multiply a a

productOfSquares a b = multiply (square a) (square b)

incrementAll list = List.map ( c -> c + 1) list

incrementAll2 = List.map ( c -> c + 1)

main = Html.p []
[ Html.text ("3 × 5 = " ++ (toString (multiply 3 5)))
, Html.br [] []
, Html.text ("4² = " ++ (toString (square 4)))
, Html.br [] []
, Html.text ("2² × 3² = " ++ (toString (productOfSquares 2 3)))
, Html.br [] []
, Html.text ("incrementAll [1, 2, 3] = " ++ (toString (incrementAll [1, 2, 3])))
, Html.br [] []
, Html.text ("incrementAll2 [1, 2, 3] = " ++ (toString (incrementAll2 [1, 2, 3])))
]

What happens in these lengthy expressions in the main function? Well, the functions we defined return mostly numbers (or lists, in the case of incrementAll). So we need to convert their results into strings via the toString function (which comes from the Basics package and is imported by default). We then use ++ to append the resulting string to a string literal ("3 × 5 = ", for example) and use Html.text to convert the string into an HTML text node.
Fancy Function Application
Whoa, did you see what we did there to bring the result of one of our functions to the screen? Let’s take a look at Html.text ("3 × 5 = " ++ (toString (multiply 3 5))) for a moment. That’s a lot of parentheses right there. Elm has two operators, |> and <|, to write expressions like that in a more elegant fashion.

  • |>: Take the expression to the left of the operator and put it into the function on the right hand side.
  • <|: Take the expression to the right of the operator and put it into the function on the left hand side.

Here is the main function of the previous program, rewritten with the new operators:
main = Html.p []
[ Html.text <| "3 × 5 = " ++ (toString <| multiply 3 5)
, Html.br [] []
, Html.text <| "4² = " ++ (toString <| square 4)
, Html.br [] []
, Html.text <| "2² × 3² = " ++ (toString <| productOfSquares 2 3)
, Html.br [] []
, Html.text <| "incrementAll [1, 2, 3] = " ++ (toString <| incrementAll [1, 2, 3])
, Html.br [] []
, Html.text <| "incrementAll2 [1, 2, 3] = " ++ (toString <| incrementAll2 [1, 2, 3])
]

If you like to go a bit crazy with this, you can even rewrite

Html.text <| "3 × 5 = " ++ (toString <| multiply 3 5)

as

Html.text <| (++) "3 × 5 = " <| toString <| multiply 3 5

or

square 4 |> toString |> (++) "4² = " |> Html.text

Here we used the infix operator ++ as a non-infix function to be able to apply it with <| and |>. We also used a bit of currying again: (++) actually takes two arguments (the two strings that are to be concatenated). The expression (++) "3 × 5 = " is a partial function application, that is, we provide the first of the two arguments to yield a new function that takes only one argument, prepending "3 × 5 = " to everything that is passed to it.
To read code like this with ease, just imagine this line as the ASCII art represenation of a data pipeline. In |> style pipelines, data flows from left to right, in <| style pipelines, data flows from right to left. So, for example, to decipher a line like Html.text <| (++) "3 × 5 = " <| toString <| multiply 3 5, you start at the end (multiply 3 5), push this into the toString function to convert the number into a string, the resulting string the goes into the append function ((++)) together with the string literal and finally the concatenated string goes into the Html.text function.
This concludes the fifth episode of this blog post series on Elm. Stay tuned for the next episode. See you next Friday!
The post Elm Friday: Functions (Part V) appeared first on codecentric Blog.

Posted by crossingtheruby.com on Tue, 11/17/2015 - 02:00

Now that we have seen the view and the model, it’s time to investigate update; the third and last element of Elm’s Model-Update-View Architecture.

Continue reading…

Posted by codecentric on Fri, 11/13/2015 - 17:30

About This Series
This is the fourth post in a series of short and sweet blog posts about Elm. The stated goal of this series is to take you from “completely clueless about Elm” to “chief Elm guru”, step by step. If you have missed the previous episodes, you might want to check out the table of contents.
Hello World 2.0
This episode builds directly on the previous episode in which we built our first Hello World app in Elm. Printing a simple string is an amazing feat but surely Elm can do a bit more, right? Let’s take a first peek at how Elm works with data structures and renders them to HTML.

The following program sorts a list of names and renders them as an HTML list.

import Html

names = [ "Pearl", "Steven", "Garnet", "Amethyst" ]

main =
let
sorted = List.sort names
texts = List.map Html.text sorted
textToItem text = Html.li [] [ text ]
items = List.map textToItem texts
in
Html.ul [] items

As with every code example, you are encouraged to put this into a file and have a look at the result in the browser by running it with elm-reactor.
This example introduces several new Elm concepts. Let’s go through them one by one:

  • names is defined as a List of strings. Bonus points if get the reference.
  • The main function is the entry point into our program, just as in the Hello World example. It is a bit more involved than the last time, though.
  • The body of the main function is divided into two parts:
    • in the let part we define a bunch of things
    • which are then used in the in part
  • sorted: We use List.sort to sort the list of names in alphabetical order.
  • texts: We use List.map to apply the function Html.text to each element in the list sorted. The result is a list of HTML text elements. (Elm does not render strings to HTML directly, you always have to turn strings into HTML text elements first).
  • textToItem defines a new function on the fly, it takes one HTML text element and wraps it in an HTML li (list item) element, representing an <li> tag.
  • items: We use List.map again to apply our brand new textToItem function to each element in the texts list. The result is a list of HTML li elements.
  • Finally, in the in part of the main function, we wrap the list of li elements in an HTML ul element, rendering them as an <ul> bullet point list.

Attributes
You might have noticed the odd empty list [] literal when we used the Html.li and Html.ul functions. The reason for this is that nearly all functions from the Html module that yield an HTML tag take two arguments: a list of attributes and a list of inner elements. The first argument (the attributes) can be used to set a CSS class, inline styles, event listeners or anything else that is represented as an attribute in HTML. The second argument, the inner element list is the list of HTML elements that will be wrapped in the new HTML element.
Let’s look at this a bit closer. Here is a chunk of Elm that sets some inline styles to center the content on the page and set the font-style:

import Html
import Html.Attributes

names = [ "Pearl", "Steven", "Garnet", "Amethyst" ]

main =
let
sorted = List.sort names
texts = List.map Html.text sorted
textToItem text =
Html.li
[ Html.Attributes.style [("font-style", "italic") ] ]
[ text ]
items = List.map textToItem texts
in
Html.div
[ Html.Attributes.style
[ ("position", "absolute")
, ("width", "10em")
, ("height", "10em")
, ("top", "50%")
, ("left", "50%")
, ("transform", "translateX(-50%) translateY(-50%)")
, ("overflow", "hidden")
]
]
[ Html.ul [] items ]

We have one new import, the module Html.Attributes which bundles all attribute related functions. There are two differences to the previous example here: The li items now have a non-empty list of attributes. We use the function Html.Attributes.style to set their font-style. Also, we wrap the <ul> tag in a div, which also comes with a list of inline styles. Those styles center the div on the page.
We sneakingly introduced a new syntax element here. The style function takes a list of tuples. Tuples are a bit like lists in the very general sense that they represent collections of multiple individual items. There are two important differences: In a list, each element has the same type and lists have a variable length. The elements of a tuple can all have different types and tuples have a fixed length. The number of elements and their individual type is a part of the tuple’s type. Thus, you can’t pass a tuple with three elements (or one) into a function that expects tuples with two elements. In other words, tuples are just pairs (or triplets, quadruplets, …) of values. They are enclosed in ( and ) in Elm.
In this case, each style is a 2-tuple of strings and the argument to style is a list of such tuples.
This concludes the fourth episode of this blog post series on Elm. Stay tuned for the upcoming next episode, where we will have a closer look on types, type inference and type annotations.
The post Elm Friday: Hello World 2.0 (Part IV) appeared first on codecentric Blog.

Posted by codecentric on Fri, 11/13/2015 - 17:29

About This Series
This is the third post in a series of short and sweet blog posts about Elm. The stated goal of this series is to take you from “completely clueless about Elm” to “chief Elm guru”, step by step. If you have missed the previous episodes, you might want to check out the table of contents.

Preparations
Create a new directory, let’s say elm-playground in a convenient location, open a shell and navigate to this directory. Before we can start with the actual Elm code we need to do one little preparation step. Type the following command in your shell:
elm-package install --yes evancz/elm-html
This will install the library to render HTML elements with all its dependencies. If you are familiar with npm install, the elm-package install works in a similar fashion. We will get to Elm’s package system later in this series.
Elm Hello World
Now that this is out of the way, we can write our first app. Honouring the tradition of our craft since the dawn of time (which was 1970-01-01, I think) we start with a Hello World Elm app:
Open your favourite editor and save the following content to a file called HelloWorld.elm in the elm-playground directory:

import Html

main = Html.text "Hello, World!"

Now start elm-reactor in the same directory. This starts a web server which will compile your Elm code on the fly every time it changes.
Open http://localhost:8000/ in a browser. This shows the directory content. Click on the file HelloWorld.elm to see the result of your very first Elm app.
Understanding the Code
Let’s dissect this piece of code and start with the bottom line. Every Elm app needs a main function that serves as the entry point. This function needs to produce some HTML. Our particular main function takes no arguments and produces a constant Html.text element with the given string as its content.
Html.text itself is a function from the module Html, which we imported in the first line. This is a module from the package evancz/elm-html, the one we installed via elm-package install earlier. When calling any function from the Html module (like div, span or text) we need to prefix it with the module name, that is, Html.div, Html.span or, as in this case Html.text. There are ways around this restriction if you prefer brevity over verbosity in your code — we’ll get to that later when we talk about the import statement in detail.
Live Reload
Now change the string “Hello, World!” in your editor to something else, say “Elm rocks!” and save the file. If you reload the page in the browser, elm-reactor will automatically recompile the file and show the new result.
That’s already pretty nice but elm-reactor can do better. Head to http://localhost:8000/ again. This time, instead of clicking on HelloWorld.elm, click the little wrench icon next to it. This opens our app in the debugger. The same can be achieved by appending ?debug to the URL, that is, opening http://localhost:8000/HelloWorld.elm?debug.
Let’s ignore the debug panel on the right for now. Change the text “Elm Rocks!” again and save the file. The Elm debugger will notice the change, recompile and automatically reload the browser without any further action on your side. Pretty neat, huh?
This concludes the third episode of this blog post series on Elm. Make sure to check out the next episode, where we will move past the simple Hello World example and dive a bit deeper into the Elm language.
The post Elm Friday: Hello World (Part III) appeared first on codecentric Blog.

Posted by codecentric on Fri, 11/13/2015 - 17:29

About This Series
This is the second post in a series of short and sweet blog posts about Elm. The stated goal of this series is to take you from “completely clueless about Elm” to “chief Elm guru”, step by step. If you have missed the previous episodes, you might want to check out the table of contents.
Installing Elm
Now that we know what Elm is, we’re all eager to get our hands dirty with it right? There are actually multiple ways to install Elm. There are installers for Windows and Mac available on http://elm-lang.org/install. If you happen to use one of these operating systems, use the installers. You’re a bit out of luck on Linux, since there is no Linux installer. You could build Elm from source, but this would require you to install and set up the Haskell Platform (Elm is build in Haskell) which can be a real pain in the rear. The recommended way to get up and running on Linux is to install Elm via npm:

  • Make sure Node and npm are installed.
  • npm install -g elm
  • That’s it.

Of course this also works on the other platforms.
No matter how you installed Elm, you can (and should) test your Elm installation by typing
elm-make --version
which should produce a response like this:

elm-make 0.2 (Elm Platform 0.15.1)

Usage: elm-make [FILES...] [--output FILE] [--yes] [--report FORMAT] [--warn]
[--docs FILE]
build Elm projects

Available options:
-h,--help Show this help text
--output FILE Write output to FILE.
--yes Reply 'yes' to all automated prompts.
--report FORMAT Format of error and warning reports (e.g.
--report=json)
--warn Report warnings to improve code quality.
--docs FILE Write documentation to FILE as JSON.

To learn more about a particular command run:
elm-make COMMAND --help

This concludes the second episode of this blog post series on Elm. Make sure to check out the next episode, where we finally start to get our hands dirty with some Elm code.
The post Elm Friday: Installing Elm (Part II) appeared first on codecentric Blog.