Developers Club geek daily blog

Simple algebraic data types

2 years, 10 months ago
It is the sixth article from the cycle "The Category Theory for Programmers". The previous articles were already published on Habré:
0. The category theory for programmers: preface
1. Category: composition essence
2. Types and functions
3. Categories, big and small
4. Kleysli's categories
5. Works and koproizvedeniye

In the previous article basic operations over types were considered: work and koproizvedeniye. Now we will show that the combination of these mechanisms allows to construct many of daily data structures. Such creation has essential applied relevance. For example, if we are able to check base data types for equality, and also we know how to reduce equality of work and a koproizvedeniye to equality a component, then operators of equality for composite types it is possible to display automatically. In Haskell for an extensive subset of composite types operators of equality and comparison, converting at line and back and many other operations are automatically brought.

Let's consider in more detail the place of work and a koproizvedeniye of types in programming.

Work of types

Canonical implementation of work of types in programming languages is a couple. In Haskell of steam is a primitive designer of types, and in C ++ it is rather difficult template from standard library.
Strictly speaking, work of types is not commutative: it is impossible to substitute couple of type (Int, Bool) instead of (Bool, Int), though they also contain the same data. However work is commutative to within the isomorphism set by function swap, which back to:
swap :: (a, b) -> (b, a)
swap (x, y) = (y, x)

It is possible to consider such couples as different formats of storage of the same information as big endian and little endian.

Read more »

Haskell for VKontakte, JavaScript and ReactJS, Or "The stranger against Simpsonov"

2 years, 11 months ago
This post is attempt to add couple of drops of fuel to the machine of promotion Haskell, showing its use in daily tasks.

As those we will consider the following:

  • We implement a packet of access to API VKontakte.
    The code will work both in "native" applications, and in the JavaScript applications through GHCJS, the compiler Haskell in JavaScript
  • Let's write a one-page web application, using our API

Read more »

"Terrible" abstractions of Haskell without mathematics and without code (almost). Part I

2 years, 11 months ago
— For what monads are necessary?
— To separate pure calculations from ghost effects.
(from network discussions about the Haskell language)

Sherlock Holmes and doctor Watson fly in the balloon. Get to dense fog and lose orientation. Here a small gleam — and they see on the earth of the person.
— Dear, whether you will prompt where we are?
— In a balloon basket, the sir.
Here carries them further and they see nothing again.
— It was the mathematician, – Holmes says.
— But why?
— His answer is absolutely exact, but at the same time is absolutely useless.

When ancient Egyptians wanted to write that they counted 5 fishes, they drew 5 figures of fishes. When they wanted to write that they counted 70 people, they drew 70 figures of people. When they wanted to write that they counted in herd of 300 sheep, they … — well, generally, you understood. And ancient Egyptians until the most smart and lazy of them saw something the general in all these records suffered, and separated concept of quantity of what we count from properties of what we count. And then other smart lazy Egyptian replaced a set of sticks which people designated quantity, on much smaller quantity of signs with which short combination it was possible to replace a huge number of sticks.

What was made by these smart lazy Egyptians is called abstraction. They noticed something the general that is peculiar to all records about quantity something, and separated this general from private properties of the counted objects. If you understand sense of this abstraction which we call today numbers, and as far as it facilitated life to people, you cannot understand also abstractions of the Haskell language — all these unclear, at first sight, functors, monoides, applicative functors and monads. Despite their frightening names which came to us from the mathematical category theory it is not more difficult to understand them, than abstraction as the name "numbers". For their understanding it is not required to know either the category theory, or even mathematics in volume of high school at all (arithmeticians it is quite enough). And it is possible to explain them too, without resorting to the mathematical concepts frightening many. And sense of abstractions of the Haskell language just the same, as well as at numbers — they considerably facilitate to programmers life (and you so far do not even represent as far as!).

Read more »

Works and koproizvedeniye

2 years, 11 months ago
It is the fifth article from the cycle "The Category Theory for Programmers". The previous articles were already published on Habré in transfer Monnorochof :
0. The category theory for programmers: preface
1. Category: composition essence
2. Types and functions
3. Categories, big and small
4. Kleysli's categories

On KDPV a pig Pyotr brings on one tractor to each object of category.

Follow on shooters

The Ancient Greek playwright Euripedes wrote "Any person is similar to the environment". It is right also for the category theory. It is possible to select a certain object of category only by the description of nature of its relationship with other objects (and by itself) where the relations are morphisms.

For object definition in terms of their relationship the category theory resorts to so-called universal constructions. For this purpose it is possible to select some template, the chart from objects and morphisms of a certain form and to consider all constructions of the considered category suitable under it. If the template is rather widespread and the category is rather big, then probably the found constructions will be very much and many. The idea of universal construction consists in arranging constructions under some law and to select the most suitable.

This process can be compared to net search. The request of the user is our template. If the request is not really specific, then in reply the search engine will issue a set of suitable documents, only part of which are relevant. To exclude irrelevant answers, the user specifies request that increases search accuracy. Eventually the search engine will range coincidence and if carries, the required result will be in the list head.

Read more »

Interview with Audrey Tan, part 1

3 years ago

Audrey Tang first of all is known as the creator and developer Pugs, Perl 6 User's Golfing System, implementations of Perl 6 on Haskell which appeared on February 1, 2005 and was the most actively developed and most complete implementation for that time.

Read more »

Kotlin ❤ FP

3 years, 1 month ago
I offer readers of "Habrakhabr" loose translation of the article "Functional programming in Kotlin". The author of the publication — Mike Hearn.


Those who use .NET, for certain heard about F#, universal functional programming language for CLR. Programmers out of .NET of community most likely know about functional programming in connection with the Haskell language.

Anyway, I suspect that similar language, but for JVM, with the developed tools and without need to do everything in functional style would please much.

Kotlin ( from JetBrains can be put out the tongue only at the sweetened Java: syntax conventions, autooutput of types (type inference) and to volume similar trifles. But under plain cover it is possible to find all most popular and progressive constructions of functional languages in it.

Read more »

Clear code free monads

3 years, 3 months ago
From the translator:
It is the loose translation of the article "Purify code using free monads" of Gabriel of Gonzales devoted to use of free monads for representation of code as syntax tree with the subsequent managed interpretation.
On Habré there are other articles of Gabriel — "Cooperative flows from scratch in 33 lines on Haskell" and "Than free monads are good".
For reading of this article it is necessary to know that such free monad and why it is functor and monad. It is possible to learn about it in the specified two transfers or in article to which the author refers.
All notes of the translator are italicized.
According to all notes connected with transfer address in pm.

Experienced programmers on Haskell often advise beginners to do programs so pure as far as it is possible. Function is called pure if it determined (the returned value unambiguously is defined by values of all formal arguments) also has no ghost effects (that is does not change execution environment status). In classical mathematics, λ-исчислении and combinatory logic all functions pure. Purity provides set of practical advantages:
  • it is possible to prove formally some properties of the written code,
  • besides, it is possible to survey easily code and to tell that it does,
  • at last, it is possible to banish through QuickCheck.

For demonstration I will use such unpretentious program echo:
import System.Exit

main = do x <- getLine
          putStrLn x
          putStrLn "Finished"

In the provided program, however, there is one shortcoming: in it the business logic and ghost effects are mixed. In specific case in it there is nothing bad, I always so write unpretentious programs which I can hold entirely in the head. However, I hope you to interest in cool pieces which turn out when ghost effects are separated from business logic.

Read more »

Приглашаем на

3 years, 3 months ago

15 августа состоится FPConf — первая в России конференция по функциональному программированию. В двух потоках однодневной конференции будут доклады о Scala, F#, Erlang, Clojure, Haskell и функциональных подходах в привычных Ruby, Python и Java.

Мы искренне считаем, что функциональные подходы сегодня — новый мэйнстрим, точка развития отрасли и полезный инструментарий, который нужен высококлассному разработчику для решения сложных и интересных задач. Прошло время, когда можно ограничиться одним технологическим стеком и быть востребованным. Большие данные, возрастающие нагрузки, профессиональное любопытство и желание развиваться приводят все больше людей к изучению монад, лямбд, замыканий и иммутабельности.

Поэтому, мы приглашаем как опытных функциональщиков, так и тех, кто только хочет получить вдохновение и обзор тем для первого изучения :)

Доклады от представителей JetBrains, Лаборатории Касперского, 2ГИС,, Mashine Zone, Luxoft, Sputnik и многих других.
Цена билета сейчас — 7000 рублей. Регистрация тут.


image Эдвард Кметт, Chair of the Haskell Core Libraries Committee
Functional programming shows us that working with immutable structures makes it easy to reason about parallelism, non-determinism, and other effects, but along the way we lose the familiar notion of a field accessor. «Getters and setters» don't make sense as such in an immutable world. Lenses provide us a way to regain that lost functionality and more besides, acting as a form of «functional reference».
On the flip side, in the process of constructing the lenslibraryfor Haskell, I've found a related notion, that of a Prism, to be equally useful for working with case matching on ADTs, handling extensible exceptions, as well as working with semi-structured data such as JSON, XML and the like. However, surprisingly little has been said about them before now.
This talk will explore the roles each of these abstractions play and why you as a developer should care about them.

Read more »

Example of solution typical OOP of task in the Haskell language

3 years, 3 months ago
Let's consider typical task, that usually are considered "OOP-eshnymi". There is list of these (objects) having not identical structures (on scientific, the heterogeneous list) at what, over everyone it is necessary to execute identical actions – on simple, everyone can be transferred to certain function.

Read more »

The code generator for Haskell

3 years, 5 months ago
Some time ago I have decided to experiment with microservices on Haskell. The architecture of the project means creation of large number of micro projects, each of which is responsible for one small volume of tasks. Through some time to me has bothered to create these projects manually, and also to write sample code for each entity from DB. I have developed the small utility allowing to generate sample code for solution of this problem. Under cat — is more detailed.

Read more »