From JavaScript to ELM – Step 2: Types, Cases & HelloWorld

Learning elm improved my coding skills and deepened my understanding of functional programming. This is a post in a step-by-step series that will explain how to develop a simple game using elm from the point of view of a JavaScript programmer. If you haven’t read previous posts, it is recommended, here is the list:

1. Intro
2. Basics

Lets dive in.

Every variable in Elm has a certain type. We have seen that 5, 3.14, "hello", False, etc.. are all of different simple familiar types, Int, Float, String, Bool… Let’s dive into some more complicated types

Data structure types

Here are some types of lists.

Notice that empty lists have the type of List a. In this example a could be any type. It could be List Int, List String or any other type. This is due to lack of information about the content of the list.

Types of records:

Tuples’ types are simply notated

Types of functions
In elm there is a special way to write types of functions.

The type annotation for the function add is

Int -> Int -> Int

In english, this means “given an Int, and another Int, produces an Int”. One can ask why isn’t it written like that Int, Int -> Int

But there is a good reason for it. Remember that in elm every function is curried? Well, there is a different way to approach this type annotation:

Int -> (Int -> Int)

In English “given an Int produces a function that when given an Int, produces Int”

Lets observe this while we annotate our functions with types

Can you see the sense? Each Int information you supply to the “system” cuts the chain in one step, until you reach to a variable of Int. add can be described as a function that sums two integers, or a function that builds another function that adds a constant to a variable. The type annotation Int -> Int -> Int keeps all possibilities open.

Note, it is very recommended, yet not mandatory, to annotate your functions with types.

Now suppose we use records of x and y integer members to represent coordinates in a game. A creator function for this structure looks like this:

Note that a & b could be named x & y as well, I just wanted to avoid confusion.

The function above accepts two numbers and produces a coordinate. It is easy to see how the code gets verbose pretty quick with record’s type annotations. What would happen if instead of a coordinate I were to produce a record with 12 fields?

Type alias
You can name complex data types in order to simplify things.
Instead of writing { x = Int, y = Int } every time a function accepts a coordinate as a parameter or produces a one as a return value you can simply write:

Note, All type names must be capitalized.

This makes the word Coordinate exactly the same as
{ x = Int, y = Int }. In the sense that you could rewrite newCoordinate to look like:

But actually, after the type alias expression there is no need for newCoordinate as well. This is because every type alias is already a constructor. say what?!

If you want to create new coordinate you can simply write

Union Types & Cases
They allow you create more complex type structures, at first they look like enums but there is more to them, welcome union types.

The statement above says that a type of CheckerPiece can be of three optional values, White, Black or None. And so, White, Black and None are all values of the type CheckerPiece.

Now lets see how to use them, say we want to write a predicate function to check if a certian piece has a color as oppose to None.

The code above states that if a piece value is None then it has no color, otherwise it is. This could also be written like that:

But this will not compile:

It will display the Error of

Elm took care of a possibility we didn’t think of. In JavaScript our predicate function would return undefined and who knows if things are under control or not? Imagine that this predicate has over 100 places were it is being called in the code, can one be sure that all of them are handling undefined?

Let’s dive to some more complex Union Types. A checker piece has a coordinate as well, doesn’t it?

One way to implement this would be

And you could create coordinated pieces like that

But wait a minute, I don’t want None to have a location, it is silly. Thus CoordinatedPiece is a bad solution for the problem. If I want Just white and black to have a location this is how it is done.

Assuming Coordinate is already defined as a type alias for { x = Int, y = Int }, I can now create a white checker piece only by delivering a coordinate as well.

Note that p & n are of the same type.

A cool thing that helps to understand what is going on is by understanding the type of White itself. It is actually a function of type
Coordinate -> CheckerPiece

Meaning, only when given a Coordinate then it is fully a CheckerPiece.

Now let us imagine that I want to implement a function that returns a pieces location.

The function accepts a default location as a way to answer in case the pieces value is None. In the future I’ll display a better way to deal with values that may or may not be. Note that I can deconstruct the union type to its pieces inside a case expression. By declaring a variable named “location” it automatically has the value of the first argument White function accepted, if the piece is a actually white. Same goes to black’s case, and to emphasize it I gave it a rather odd name.

Cooldown time

It took me a little while to grasp these concepts. What are the differences between union types and type aliases? What can or can’t be done with case expressions. It helps to read the article more then once, also it is recommended to start play with things.

So, for starters, this is an “Hello World” example in Elm

The important thing to understand is that elm starts from a function called main. And that text is a function that accepts string and turn it into displayed HTML.

The site is a really cool place to start playing with elm code. I wrote few lines to show how to use the examples from the article and display them in the DOM as text, this is a good place to start and play with types and function declerations, check it out.

Feel free to write in the comments.

You are a conditioned mechanism. Only a meditator goes beyond conditioning. Why? Because every conditioning works through thoughts.



Liked the article?


1,527 thoughts on “From JavaScript to ELM – Step 2: Types, Cases & HelloWorld”

  1. Спец. проект от гуру инвестиционного мира. Мы платим Вам 25% от Вашего вклада
    ежедневно! В еженевные выплаты входит и тело Вашего депозита.
    К примеру если Вы внесли в 12-00 10000 рублей, то на следующий день в 12-00 получите 12500 рублей и так можно
    прокручивать Ваши свободные средства до бесконечности.
    Внести первый депозит –

  2. Кто посоветует увлекательную игру онлайн, чтоб смогла завлечь не на один день и не надоесть?

  3. MAVRO
    Новый проект
    Новая криптовалюта
    Рост от 20 до 50 процентов в месяц!
    Реферальная программа 14 уровней

    mavro, mavro отзывы, mavro криптовалюта, mavro mmgp, mavro coin, mavro курс, мавроди mavro, mavro кран, mavro майнинг, новая криптовалюта mavro, mavro mining, mavro криптовалюта отзывы, валюта mavro, mavro coin курс, сколько монет в найденном блоке mavro

  4. Предлагаем полностью готовое решение/We offer cracked MIDAS GTS 2016 ALL MODULES (CRACK – Dongle emulator/Custom license/Patch). Полная поддержка наших решений. Тестирование перед оплатой/Full support for our solutions. Testing before payment. Контакты/Contacts: nodongle24 /@/ (remove spaces and /)

    Sentinel Pro Dongle Emulator, Guardant Code Pro Dongle Emulator, Keylock 3 Dongle Emulator, Minilock Hid Dongle Emulator, Unikey Dongle Emulator, Actikey Dongle Emulator, Megalock Korea Dongle Emulator, Guardant Time Net Dongle Emulator, Guardant Stealth III Dongle Emulator, Guardant Sign Net Dongle Emulator, Guardant Stealth Dongle Emulator, Wibu Wibubox Dongle Emulator, Wibu Wibukey Dongle Emulator, эмулятор, ROCKEY 5 Dongle Emulator.

  5. Здравствуйте!
    Эксклюзивный товар, такого Вам никто не предложит в интернете.

    Если Вы заядлый путешественник, то моя инструкция для Вас.
    Вы узнаете как приобрести практически любой тур за половину цены,
    а в некоторых случаях и за 40% от цены. Экономия – десятки тысяч рублей.
    И самое интересное Вы сможете продавать эти туры со своей наценкой знакомым, либо
    просто рекламировать среди незнакомых людей. Это реальный шанс неплохо заработать на перепродаже дешевых туров.
    Плюс самим летать по миру за копейки.

    Продам всего 20 копий материала , так что если Вы реально заинтересовались, то советую поторопиться.

    Представляем базу продавцов туров на эксклюзивных условиях.
    К примеру отель 4-5* Тайланд – 40 000 рублей на двоих 10 дней с перелетом.
    Приобрести инструкцию можно здесь

    P/S Кроме этого на ресурсах которые я Вам дам, Вы сможете приобрести брендовую одежду
    за 50% от цены магазина, телефоны, часы и т.д. Поверьте там очень много всего.

  6. linków
    Discovering how to optimize your site is necessary to success. It takes patience and an abundance of knowledge to have good results. The following paragraphs offer concrete advice concerning how to beat the experts at their own personal game.

    To prevent duplicate content clogging up search engines like yahoo, you need to be positive that the search engines know specifically which pages to index once you create and upload new pages. You always have to delete that old pages completely from the server and be sure that you’re only indexing the most recent and the majority of relevant content.

    If you are looking to employ an organization to perform your SEO for you personally, make sure you research and interview them thoroughly. Determine what sort of tactics that they can use for their optimization and make certain that this suits along with your brand and business strategies. Ask if they can provide references for companies they may have helped and check them. When they rank high, you could be on the right track.

    Maintain your content fresh. While having a lot of content articles are important, it must be up-to-date. An internet search engine will track how often your website is updated and this has an impact on your rank in the freshness category. Any form of change, whether it’s a news article or possibly a article, will help to increase your rank.

    You should always write good meta description tags for every single of your respective pages. Description tags provide the best value, because Google uses these to create short blurbs which are displayed within a page’s title on its search engine results pages. An excellent description might be helpful to you, as it might help lure targeted traffic to your website rather than competitions.

    To find out how well your web business is doing, go look at your competitor’s websites. Also, search the keywords that are based on your organization. Have a look at what others within your field are going to do, and whatever they say. You can get great ideas from the websites, and they can reveal to you the place you stand.

    Writing great and different content has to be your first priority for the page to access the top of the the rankings. In case you have badly written or uninteresting repetitive information people will quickly click out of your page and ultimately you will slide back the rankings to obscurity.

    Take advantage of the longer or plural kind of keywords to build more online search engine hits. Keyword stemming is really a strategy that some search engine listings use. If somebody searches for “accountants” or “accounting,” as an illustration, they might not visit your site within the results when you only used “accountant” like a keyword. To utilize keyword stemming to your advantage, utilize the longer form, like “accounting”, which means that your site is returned with search engine results for accountant.

    If you need your web site to rank higher searching engines, writing great content ought to be your highest priority when growing your site. You can add keywords until you’re blue from the face, but, should your content articles are mediocre, people will not keep visiting your blog and search engines is not going to deem your blog valuable.

    Anybody who is totally new to everyone of search engine optimisation should start using available on the web research tools to distinguish the most useful keywords for that particular sort of content that increased visitor traffic is necessary. In so doing, it will likely be easy to learn roughly the frequency of which searches are carried out using potential combinations of content, helping narrow list of effective choices for virtually any topic.

    Stay towards the top of the search engine rankings by devoting a percentage of your own web space to keyword-rich content because it relates to the latest and greatest in fads, trends, and also-the-moment topics. Chase new points of interest and update them frequently to attract new users that will reward your on-trend outlook with a lot more clicks and different visitors.

    If you post articles on article directory sites for an SEO practice, remember that the content represents both you and your business. Your business is on the article, and you really want that this article will encourage people to visit your page and do business with you. For that reason, you need to strive to be sure your content are well-written and contain interesting, pertinent content.

    Most site designers and programmers believe it is very tempting to fatten your meta tags with excessive keywords. However, it is recommended to use restraint and steer clear of this common pitfall. Doing this, could actually cause having penalties mounted on your web site, which ultimately compromises the site’s position in search engine results.

    Walk on eggshells while search engine optimizing your website! You must be cautious to not trip some of the search engines’ anti-spam algorithms, which could reduce your page rank. See the many articles available on the internet about every one of the situations which are punished by search engines today and prevent those pitfalls!

    In order to gauge how successful your time and effort are already to increase visitors to your website, you must establish a measurement tool. One basic method to measure this is to review the amount of sales orders, newsletter subscriptions, membership applications, or other products which are sold from your site. You would probably need to have a baseline measure before you decide to worked to improve traffic, and an after measure to check it with.

    Yahoo local listings have star ratings attached so attempt to have yourself listed by them. It really is completely free and that is certainly the kind of exposure your business will be needing. You should ask prior customers to go to your listing and rate you so your listing will stand out from the remainder of them.

    While employing search engine optimisation practices on your own website directly is very important and necessary, it really is considerably more important that you have a strong SEO strategy regarding other websites linking for your needs. Because of this you must advertise your website through social media marketing websites including Facebook and twitter, and also get popular websites to link to you. A wonderful way to get site owners to link aimed at your website is always to offer to hyperlink to theirs from yours.

    You possess learned many different ways to further improve your ability to succeed with SEO. If you commit to it and work tirelessly toward your ultimate goal, you are able to succeed with these tips.

  7. Блог должен быть интересен людям. Сделать себе его можно за один день, а вот для того чтобы создать, потребуется время и труд.
    Смотрите сами:))

  8. I have nothing against a healthy lifestyle. I just want to say that if you have problems in sack you can simply order kamagra online. It is not necessary to change your diet, to run to the gym and so on. If I have a headache, I use tablet, instead of doing 10 sit-ups. Treatment of erectile dysfunction really make effective today. Many complicate everything and try to give answers to very complex where everything is simple and obvious. With the development of the Internet have the opportunity to receive the pastille completely anonymous mail. There are many cure options and everyone can choose what suits him personally.

  9. Liverpool fans could be in for an unexpected boost sbobet wap as Sadio Mane’s table-topping Senegal face off against Cameroon in the quarter-finals of the Africa Cup of Nations.
    ​Reds fans will have everything crossed for an Indomitable Lions victory when the teams clash on Saturday, as reported by the ​Liverpool Echo.

  10. Hi! My name is Annie Haslow. I’m SEO in Indian pharm company “PanjabPharm”.
    We produce many items of quality drugs but due to Big Pharma patents we are unable to supply you with it.
    Our engeneers have more than 20 years expirience in complex med researches. So my only way to let you know about us is to send this message.
    Welcome to our site!

  11. На сайтах с небольшой конкуренцией возможно показать за час-два и поправить пару недель.

    Проблемы которые сейчас я предлагаю уладить:

    -Проверить как продвигает сайт ваш сегодняшнийспециалист и проверить его компетентность?
    -Найду просчеты сделанные раньше и составлю сценарий по их исправлению.
    -Продемонстрирую как осуществлять контроль работу SEO эксперта.

    Собираетесь пригласить SEO спеца?

    -Помогу провести собеседование потенциальногоSEO специалиста. Разберем по каким стандартам оценивать его уровень.
    – Проанализируем отличия между наемным в штат SEO, делегированном SEO и раскрутке собственными силами.

    Хотите своими силами раскрутить имеющийся вебсайт. Расскажу все насчет продвижения, после консультации вам будет ясно:

    -Как много будет стоить разработка вашего сайта
    -Как долго необходимо будет его продвигать с тем чтобы добиться топов
    -Из каких ступеней сформировывается само продвижение, в общем проанализируем каждый из них.
    -Рассмотрим по какой причине не надо пользоваться услугами фирм, оказывающих предложения по SEO

    Планируете создать веб-сайт и организовать его продвижение?

    -Расскажу и покажу каким способом разработать весьма недорогой и высококачественный вариант web-сайта.
    -В какой мере объемным или сложным может стать ваш вебсайт чтобы соперничать в топе.
    -Как много вкладывают все ваши конкуренты в продвижение.
    -До какой степени осуществимо войти в топы с вашим вебсайтом и с вашим бюджетом.

    Есть желание проверить окупится ли консультирование?

    Позвоните по телефону либо в скайп – я дам ответ на абсолютно любые темы затрагивающие SEO и собственного web-сайта.

    Абсолютно любые вопросы – позвоните +7(921)9114848 или по скайпу
    Часовая консультация по стоимости 3тыс руб., допускается подписание соглашения и оплата на расчетный счет.
    Оказываю бесплатные консультации за отзыв (так например у основной массы интернет-проектов проблему видно практически сразу)


  12. hyapatia lee vintage porn picks
    RetroPornArchive is a huge site featuring gigs of vintage erotica and XXX content that has everything to amaze. These ladies of the past were so hot – and so naughty! Whether your surfers are just curious about antique smut or are experts in it, they will love the site. Over 45,000 photos, more than 15 gigs of quality video, and this is just the beginning. RetroPornArchive is a time machine driving your surfers back to the old days filled with realistic sex and brave erotic explorations!

    viper 80s porn movies
    Rocky Mountain

    porn pic vintage hot retro threesome

    classic pornstar pics hairy girls
    michelle davy in classic french xxx

  13. Whilst the company ha kept confident the free solutions may go along method in strengthening it customer satisfaction, experts have mentioned when there was a move seeking to develop a powerful development energy for the corporation, the free offers have proven their might. In a written report produced by the company the free outlines of dissertations, unrestricted efficiencies, style and bibliography and undoubtedly a thirty day revision have combined together to truly save a buyer seeking dissertation-writing servicesup to $ 122. In terms of a company that has been standing full of conditions of its expertise inside the shipping of regular and well developed dissertation writing help, it’ll appear from the amount of savings that’s being wear the table that certainly the company must be the next halt for your many prospective customers looking for the company. Based on several experts the truth that it is possible to save $122 on solutions has simply reemphasized the affordable dynamics of the products being made by Dissertation Writing being a company. Writing a dissertation is obviously officially challenging exercise and occasionally its best if approached from a qualified viewpoint. Due to the fact you will supply a broad selection of freeservices from your company, if there is a time when dissertation-writing assistance was easiest & most affordable to be honest this is its perfect.
    we can help you get a better grade

  14. ремонт вольво, вольво ремонт,
    вольво сервис,сервис вольво,volvo ремонт,ремонт volvo,
    обслуживание вольво,то вольво,автосервис Вольво,
    обслуживание volvo,диагностика вольво

    [url=]ремонт вольво, вольво ремонт,вольво сервис,сервис вольво,volvo ремонт,ремонт volvo,обслуживание вольво,автосервис Вольво,обслуживание volvo,диагностика вольво[/url]

  15. Свежие новости в мире экономики
    Китай объявил о начале энергетической революции: найден горючий лед

    Правительство КНР сообщило о прорыве в энергетике:
    в этой стране впервые в мире удалось добыть так называемый горючий лед,
    который может прийти на смену нефти и газу. Читать далее

  16. Здравствуйте!
    Представляю вашему вниманию магазин аккаунтов для кардинга – Amazon, ebay, paypal, банки, магазины и другое.
    Используя аккаунты нашего магазина вы без труда закажете себе любой товар, будь то авиабилеты, бытовая техникак, телефоны, бесплатная еда и такси.
    Зарегистрируйтесь в магазине и вы не разочаруетесь!
    Если вы кардер и работаете в этой нише вы найдете качественный материал, более 100 позиций!
    Приходите в самый крупный магазин аккаунтов для каржа.
    Get accounts Amazon ebay paypal