#functional_programming
Explore tagged Tumblr posts
Link
This article will show you how to set up an Http4s server to correctly protect against cross-origin requests and CSRF.
0 notes
Text
Elixir and Phoenix – A Review
So I've been spending some time recently learning about Elixir and Phoenix. I thought I'd share my experiences here, maybe someone will find it useful. If you've never heard of it, Elixir is a new(-ish) programming language that borrows a lot of syntax from Ruby. However, even though it looks quite similar on the surface, it's really a very different language.
Ruby is a object oriented, multi-paradigm language (meaning it supports imperative and functional programming styles). It's also interpreted, meaning that there is no compilation step. This is what makes many of the advanced features in Ruby work, but it's also the reason why it is rather slow compared to languages like Java or C, which involve a compilation step.
Elixir is similar to Java, in the sense that there is a compiler, but instead of machine code, it produces byte code that runs on a virtual machine. In the case of Elixir, this virtual machine is Erlang, a language created over 30 years ago by the Swedish telecom company Ericsson for use in their telecommunications equipment.
It turns out that Erlang has many features that are very desirable for building web applications, such as high performance, fault tolerance, and the ability to support many millions of simultaneous connections. It also has very good support for multi-core CPUs, something that is more and more important these days, now that even the smartphone in your pocket likely has multiple cores. However, Erlang's syntax is quite dated, so Elixir aims to bring Erlang into the 21st century.
Phoenix on the other hand is a web framework for Elixir. It's heavily inspired by Ruby on Rails and indeed shares many of the same features. However, it is generally at least an order of magnitude faster. Instead of taking several milliseconds, it can answer most requests in a matter of microseconds.
There is a cost, however, and that's learning a new programming paradigm. Elixir is a functional programming language, meaning that there are no objects, only functions. Furthermore, functions have to be "pure" in the mathematical sense, that is, they can have no side effects.
All data in Elixir is immutable by default, meaning it cannot be changed. If you want to make changes to a variable, you need to return a new copy that includes the changes. If this sounds expensive to you, then keep in mind that the developers thought of this and heavily optimized the compiler for this use case, so in practice, this is much faster that you'd think. Behind the scenes, the language uses many tricks to make this incredibly cheap. For example, inserting an element at the beginning of a linked list does not need to copy the entire list – since the tail of the list is guaranteed to never change, the new list can be constructed by simply making a new head and linking it to the old list.
The advantage of having immutable data is that it allows for easy parallelization. The biggest problem that languages like Ruby have with parallelization is when data needs to be shared between two threads. If two separate threads want to access the same data (say, one wants to read and another wants to write), that creates a conflict. They have to synchronize somehow, so that one thread has to wait until the other is done before accessing the shared data. This can lead to many difficult-to-resolve bugs.
In Elixir, everything is immutable, so there is no problem sharing data between threads. If one thread wants to make changes, it automatically gets its own copy of the data.
While it takes a bit of practice, but after a while it's not that difficult thinking only in functions. A web server is really just a collection of functions (AWS lambda makes that pretty clear). A request, consisting of HTTP method, URL, headers and body (for POST/PUT/PATCH) goes in, HTML comes out. Since HTTP is by definition a stateless protocol, the functional paradigm is a perfect match for this use case.
Of course, in a web app, it usually takes many steps to produce the desired response. Phoenix gives you the tools to compose your functions out of many smaller functions, and it also provides a convention to help organize them in a sensible way.
Similar to Rails, Phoenix uses the MVC (Model, View, Controller) pattern, but it introduces a few more layers to keep things neat. In Phoenix, every controller has a single view module, which in turn can have several templates. Any helper functions that are used in the view (which go into a helper module in Rails) go into the view module, assuring that they are only available to the templates that need them, not application-wide like in Rails.
Phoenix also adds a new layer of abstraction between controllers and models (called a “context”), which absorbs all the database queries. This fixes a big problem with Rails, where models often grow tremendously large because they have to deal with both business logic and database logic. Phoenix draws a clear line, separating the business logic from the database code.
Another interesting aspect of Phoenix is the idea of pipelines, which fixes another big problem of Rails: middleware. If you've ever worked on a large Rails app, it can be quite difficult figuring out exactly what filters are run for a request and in what order. Even more so if you have an application that has both an HTML frontend and an API — In this case, you often want a different set of filters to apply for API requests than you have for HTML requests. Phoenix solves this by letting you combine all the filters (which it calls "plugs") into a pipeline and then giving you a way to decide which pipeline a request should be routed through. If it's a browser request, you send it through the :browser pipeline. If it’s an API request, you send it through the :api pipeline. Neat.
All in all, it makes for quite an interesting framework. While I wouldn't exactly recommend it to someone brand new to web programming (Rails is much more beginner friendly than Phoenix), it's easy enough to pick up for someone with a few years of Rails on their back. It does take some getting used to, however – especially Ecto, the persistence layer, feels rather clunky compared to elegance of Rails's ActiveRecord (although it is no less powerful). However, the enormous performance gain might well be worth making the switch for. A single app server running Elixir and Phoenix can easily replace 10 Rails servers (and probably have room left to grow). I'm looking forward to learn more in the future.
0 notes
Text
Work stealing이란?
Work stealing
패러랠 컴퓨팅(parallel computing) 환경에서, working stealing은 다중 쓰레드를 활용한 컴퓨터 프로그램을 위한 스케쥴링(scheduling) 전략이다. working stealing은 동적인 다중 쓰레드 계산 실행상의 문제를 해결하는데, 그중 하나는 고정된 갯수의 프로세서(혹은 코어)를 가진, 정적인 다중 쓰레드 기반의 컴퓨터 상에서 새로운 실행 쓰레드를 생성하는 것이다. Working stealing은 실행 시간, 메모리 사용량 그리고 프로세서간 통신 측면에서 굉장히 효율적이다.
Working stealing 스케쥴러상에서, 컴퓨터 시스템의 개별 프로세서는 계산 작업 그리고 쓰레드와 같은 작업 항목을 위한 큐(queue)를 가지고 있다. 개별 작업 항목은 순차적으로 실행되어야 할 일련의 작업 지시 사항들로 이루어져 있는데, 실제 실행 과정에서 하나의 작업 항목은 동시에 처리 될 수 있는 새로운 작업 항목을 생성할 수도 있다. 이런 새로운 작업 항목들은 생성된 초기엔 해당 작업 항목을 처리할 프로세서의 큐에 포함된다. 특정 프로세서가 자신의 모든 작업 항목 처리를 완료 하였을때, 다른 프로세서의 큐를 살펴보고 처리 되지 않은 작업 항목이 있으면 그 작업 항목을 "훔쳐"와서 처리한다. 사실 work stealing은 모든 프로세서가 유휴 상태에 빠지지 않고 스케쥴링(scheduling)의 과부하가 발생하지 않는 선에서 유휴 상태(놀고 있는) 프로세서에게 작업 계획을 재 분배한다.
Work stealing은 동적 쓰레딩처리를 위한 또 다른 접근 방법인 work sharing과는 대조 되는데, work stealing의 경우 프로세서간 프로세스 이관(migration) 처리량을 줄 일 수 있다. 그 이유는 모든 프로세서가 해야 할 일을 가지고 있다면 프로세서간 프로세스 이관은 발생하지 않기때문이다.
work sharing은 새로운 작업 항목 생성 시, 특정 프로세서에서 실행되도�� 스케쥴링 된다.
Work stealing의 아이디어(idea)는 1980년대의 Multilisp 프로그래밍 언어의 구현과 함수형 프로그래밍언어의 병렬처리를 위한 작업으로 거슬러 올라갑니다. Work stealing은 Cilk 프로그래밍 언어를 위한 스케쥴러, 자바(Java)의 fork/join 프레임워크 그리고 .NET의 Task Parallel Libary에 채용되었습니다.
Execution model
Work stealing은 병렬 처리 기법의 "엄격한" fork/join model을 위해 설계 되었습니다. Work stealing을 통해 처리되는 계산은 계산 처리의 시작을 나타내는 단일 소스(source)와 계산의 종료를 나타내는 단일 싱크(sink)를 가지는 비순환 방향 그래프(Directed acyclic graph)로 표현 할 수 있습니다. 그래프에서 각 노드(node)는 fork혹은 join을 나타냅니다. Fork들은 다중의 논리적인 쓰레드 혹은 스트랜드로 불리는 병렬처리를 생산합니다. 노드를 이어주는 선(edge)은 연속적인 계산을 의미합니다.
예를 들어 아래의 Cilk 언어 형식으로 작성된 예제를 보겠습니다.
function f(a, b): c ← fork g(a) d ← h(b) join return c + d function g(a): return a × 2 function h(a): b ← fork g(a) c ← a + 1 join return b + c
f(1, 2) 함수 호출은 아래와 같은 계산 그래프로 나타낼 수 있습니다.
출처: Wikipedia Work_stealing
위의 그래프를 보면, 두개의 선(edge)가 하나의 노드로부터 시작될때, 계산 처리들은 선위의 표기(label)로 표기되며 논리적인 병렬 처리를 말합니다. 그 두개의 선으로 표시된 계산 처리들은 병렬 혹은 순차적으로 처리될 수 있습니다. 계산 처리는 join 노드로 들어오는 선으로 표시되는 계산이 완료되면 해당 join노드에서 진행될 수 도 있습니다. 이제 스케쥴러가 해야 할 일은 전체 계산이 정확한 순서(join 노드들로 제약된)로 실행 될 수 있는 최대한 빨리 완료할 수 있는 방법으로 계산 처리들(edges)을 프로세서에 할당 하는 것입니다.
원본: https://en.wikipedia.org/wiki/Work_stealing
0 notes
Link
0 notes
Photo

GDL #1 – Kenalan dengan C#
Halo Semua! Kali ini kita akan kenalan dengan salah satu bahasa pemrograman yang menurut survei tiobe.com (hingga bulan Juni 2017) masuk jajaran 5 besar bahasa pemrograman terpopuler di dunia, yaitu... C#!.
C# atau dibaca ‘see sharp’ (jangan ‘ce pager’ yaa), merupakan bahasa pemrograman yang dikembangkan oleh Microsoft pada tahun 2000 silam. C# termasuk bahasa pemrograman yang mendukung multi-paradigm, atau mendukung lebih dari satu paradigma (cara pandang pemrograman dalam menyelesaikan suatu permasalahan) pemrograman, diantaranya strong typing, imperative, declarative, functional, generic, object-oriented dan component-oriented programming. Berikut ini garis besar maksud dari paradigma-paradigma tersebut.
Strong typing
Yang dimaksud dengan strong typing disini adalah kita harus menuliskan kode kita secara konsisten, baik saat mendeklarasikannya atau menggunakannya, harus memiliki tipe data dan memberikan nilai yang sesuai dengan tipe data variabel tersebut. Contoh nya seperti kode dibawah ini:
int tinggi = 120 + “cm”;
Kode diatas error, karena kita mencoba menggabungkan nilai numerik dengan teks pada variabel numerik.
String nama = “Eceng Gondok”; Nama = “Nasi Goreng”
Kode diatas error, karena kita memanggil variabel yang belum dideklarasikan. Kalau kalian perhatian ‘nama’ dan ‘Nama’ tidak dianggap sama walaupun karakternya sama.
Masih ada banyak contoh lainnya, lanjutkan saja baca dan ngodingnya agar makin rutin menemukan error ini :p.
Imperative
Pada paradigma ini, kita akan menuliskan kode program yang mendeskripsikan dengan jelas alur program, setiap tahap-tahapnya secara detil, yang harus diproses komputer untuk menyelesaikan suatu problem. Hal ini mengacu ke algoritma pemrograman. Contoh kode disadur dari https://timross.wordpress.com/2010/04/05/an-example-of-functional-vs-imperative-programming-in-c/ .
public int[] Translate(string word) { ArrayList numbers = new ArrayList(); foreach (char character in word) { foreach(KeyValuePair key in keys) { foreach(char c in key.Value) { if(c == character) { numbers.Add(key.Key); } } } } return (int[]) numbers.ToArray(typeof (int)); }
Declarative
Paradigma ini memiliki kesamaan seperti Imperativ, hanya saja kita dapat lebih ringkas saat mendeskripsikan tindakan yang akan dilakukan program.
Pada paradigma ini, kode program diatas (yang ada di imperative) ditulis dengan pendekatan visual atau bahasa manusia, seperti menggunakan LINQ atau XAML saat menggunakan .NET. Konsepnya sama seperti saat kita ingin mengambil data dari data base menggunakan bahasa SQL. Kode program disadur dari http://www.informit.com/articles/article.aspx?p=1330154&seqNum=4
Contoh kode imperative
List newList = new List(); foreach (var item in lists) { foreach (var number in item) { if (number % 2 == 0) { newList.Add(number); } } } newList.Reverse();
Contoh kode declarative
var query = from list in lists from num in list where num % 2 == 0 orderby num descending select num;
Jadi declarative lebih condong menggunakan LINQ. Karena memang pada dasarnya LINQ sendiri menggunakan paradigma declarative.
Functional
Merupakan paradigma yang memperlakukan proses komputasi sebagai fungsi matematika. Dengan paradigma ini, programmer akan melibatkan penyusunan problem sebagai suatu fungsi yang nantinya dieksekusi. Programmer juga mendefinsikan dengan tepat inputan fungsi serta tipe data dan nilai kembali dari pemanggilan fungsi tersebut. Functional biasa menggunakan rekursif atau pemanggilan fungsi dalam fungsi sebagai perulangan dalam menemukan solusi dari problem yang ada. Jadi, definisikan inputnya, prosesnya lalu outputnya.
Contoh kode menggunakan perulangan rekursif
static int Factorial(int n) { return n < 1 ? 1 : n * Factorial(n - 1); }
Generic
Paradigma ini memungkinkan kita mendefinisikan struktur data atau class tanpa terpaku pada tipe data yang digunakan atau diolah. Hal ini serupa dengan template yang ada di C++. Contohnya seperti class List, yaitu suatu class struktur data yang dapat menampung data dengan tipe data apa saja, hanya saja operasinya tetap sama, seperti mengakses array, menghapus, atau menambah. Jadi, kita dapat membuat suatu class atau fungsi yang dapat mengolah berbagai macam tipe data. Paradigma ini akan sering kita jumpai dalam proses pembuatan game. Berikut ini contoh kode yang disadur dari https://www.tutorialspoint.com/csharp/csharp_generics.htm
public class MyGenericArray { private T[] array; public MyGenericArray(int size) { array = new T[size + 1]; } public T getItem(int index) { return array[index]; } public void setItem(int index, T value) { array[index] = value; } }
Object-oriented
Paradigma ini pada dasarnya meng-object-kan segala sesuatu yang ada di program kita sebagai pendekatan dalam menyelesaikan problem yang ada. Object ini memiliki field dan behaviour. Bila kita ambil contoh manusia sebagai object, maka ia memiliki field tinggi dengan nilai 170, nama dengan nilai Resa, dsbnya. Sedangkan behaviour yang dimiliki seperti berjalan, makan, berlari, tidur dsb. Paradigma ini akan kita bahas lebih detail di post-post berikutnya.
Component-oriented programming
Paradigma ini menggunakan pendekatan reuse-based dalam mendefinisikan, mengimplementasi serta menyusun komponen yang independen yang nanti digunakan dalam system. Kita akan banyak menggunakan paradigma ini karena konsep ini digunakan Unity3D dalam pemberian behaviour kepada object-object yang ada dalam game.
Oh iya, kalian ndak perlu gundah bila belum betul-betul memahami paradigma-paradigma diatas. Lanjutkan saja proses belajar kalian, lama-lama juga paham.
Arsitektur dan Kompilasi
C# juga salah satu bahasa yang didesain untuk CLI atau Common Language Infrastructure, yaitu standarisasi teknis yang dikembangkan oleh Microsoft yang intinya bahasa yang dicompile dapat berjalan di platform komputer lain tanpa harus di tulis ulang. Beberapa framework yang mengimplementasikan CLI diantaranya .NET Framework, Mono, DotGNU dan Portable.NET. Kita akan bahas beberapa framework barusan.
.NET Framework adalah software framework yang didevelop Microsoft untuk mengembangkan software yang berjalan di platform Windows. Framework ini sudah terintegrasi dalam Visual Studio, sehingga seluruh bahasa yang didukung seperti C#, C++, VB, F# dan J# dapat menggunakannya. Jadi hal ini semacam paket lengkap dari Microsoft untuk developer yang ingin mengembangkan software untuk platform Windows atau Windows Phone.
https://en.wikipedia.org/wiki/File:Overview_of_the_Common_Language_Infrastructure.svg
Sedangkan, Mono Framework adalah proyek open-source Xamarin dengan tujuan mengembangkan Ecma standard-compilant yang compatible dengan .NET Framework. Hal ini menjadikan aplikasi yang dikembangkan dengan .NET Framework dapat berjalan cross-platform. Dengan dukukan Mono Framework, kita bisa mengembangkan aplikasi hybrid rasa native untuk platform Android dan IOS menggunakan C# di IDE Visual Studio 2015 keatas. Hal tersebut terjadi berkat kerja sama Microsoft dengan Xamarin (baca: akusisi). Dan... Gratis. Yeay!
Unity3D merupakan game-engine yang dikembangkan menggunakan bahasa C++. Kode yang kita tulis menggunakan C# (atau JavaScript) akan berjalan diatas framework Mono atau .NET., dalam arti yang menjalan kan kode kita bukan kode Unity3D sendiri. Saat kita menjalankan game kita di Editor Unity, kode kita akan di compiled menggunakan Mono versi 3.5, yang memiliki kompabilitas dengan .NET Framework 3.5 atau CLR 2.0. Kode tersebut akan di compile berdasarkan target platformnya. Target platform Windows dan Android akan dikompilasi dengan JIT (Just-in-time) sedangkan IOS dengan kompilasi AOT oleh Mono.
Jadi, arsitektur dan model kompilasi tersebut yang menjadikan Unity3D dapat berjalan diberbagai platform (syarat dan ketentuan berlaku).
Oke, sekian untuk post kali ini. Sampai jumpa di post berikutnya!
Referensi
http://dekodex.com/2016/01/17/mengenal-c-untuk-pemula/
https://timross.wordpress.com/2010/04/05/an-example-of-functional-vs-imperative-programming-in-c/
http://www.informit.com/articles/article.aspx?p=1330154&seqNum=4
https://www.codeproject.com/Articles/375166/Functional-programming-in-Csharp
https://www.tutorialspoint.com/csharp/csharp_generics.htm
https://en.wikipedia.org/wiki/C_Sharp_(programming_language)
https://en.wikipedia.org/wiki/Strong_and_weak_typing
https://en.wikipedia.org/wiki/Imperative_programming
https://en.wikipedia.org/wiki/Declarative_programming
https://en.wikipedia.org/wiki/Functional_programming
https://en.wikipedia.org/wiki/Generic_programming
https://en.wikipedia.org/wiki/Object-oriented_programming
https://en.wikipedia.org/wiki/.NET_Framework
https://en.wikipedia.org/wiki/Common_Language_Infrastructure
https://en.wikipedia.org/wiki/Mono_(software)
http://www.mono-project.com/docs/about-mono/dotnet-integration/
/****** READ ME ******/
Ada kritik dan saran? Silahkan isi komentar dibawah ya J Yow! Terimakasih telah berkunjung!
/****** BACA YA ******/
0 notes
Text
genba.fm
昨日 mizchi さんの #0 React vs Angular - あるいは Functional JavaScript を聴きました。
Rebuild と同じく、対談形式の場合、ラジオという媒体は相性がよいですね。今回の genba.fm は SPA の専門家同士の会話になっており、技術用語を知っていないとよくわからないため、簡単に調べました。
SPA が要求される文脈
mizchi さんによると SPA が要求される文脈は、下記の三点で基本的には差別化要素とのこと。
ユーザ体験
Electron によるデスクトップ・アプリケーション
React Native によるスマートフォン・アプリケーション
用語集
SPA: Single Page Application 単一ページで構成される Web アプリケーション。詳しくは こちら
SSR: Server Side Rendering サーバから HTML を出力する手法。従来の Web サーバに hoge.html をおくことが前提の場合、あたり前のことかと思いますが SPA のようにクライアントサイドの JS で DOM を構築するアプリケーションの場合は SSR を検討する必要があります。 SSR の目的はふたつ。イニシャルビューの高速化(いわゆるローディング画面なし)と SEO です。
BFF: Backend For Frontend こちら によると、ユーザエクスペリエンスごとにひとつの API バックエンドを用意する API バックエンドの提供パターンのこと。この BFF パターンにはふたつの取り組み方があり、例えば iOS と Android を扱う場合は BFF で両プラットフォームを扱うか、各インターフェイスごとに BFF を用意する方法(厳密な BFF モデル。こちらの後者を推奨)があるとのこと
Isomorphic もしくは Isomorphic JavaScript 同一構造という意味で、読みはアイソモフィック。最近では Universal JavaScript と呼ぶとのこと
Universal JavaScript こちら によるとクライアントやサーバに限らず、モバイルや組み込みデバイスといった環境でも実行できる JavaScript という概念のこと
Protractor AngularJS の E2E テストフレームワークのこと
Karma ブラウザで単体テストを行うためのフレームワークのこと
Next.js React ベースの Universal JavaScript フレームワーク
RxJS: Reactive Extensions for JavaScript 非同期処理のライブラリ。詳しくは こちら
TypeScript JavaScript に変換するトランスパイラの一種で AltJS 言語。開発は Microsoft
Immutability Wikipedia によると一般的なプログラミング用語の文脈においては、生成後にその状態を変えることのできないオブジェクトとのこと Immutability in JavaScript によると JavaScript の文字列と数字は Immutable ですが、配列やオブジェクトには Immutable ではありません。そこで Immutable.js を用いることで Immutable な配列を実装することが可能になります(類似のライブラリは他にいくつかあります) Immutable data structure によって 開発が簡単になる という利点があります 参照透過性と関係がありそうですが不明です…
Immutable.js Facebook 開発の Immutable data structure を扱うためのライブラリ
DI: Dependency Injection Dependency Injection とは 使われる側のオブジェクト(サービス)を、使うオブジェクト(クライアント)に渡すデザインパターンのこと とのこと もうすこし具体的に書くならば 本体の処理が依存している外部との接続箇所を変更可能にしておいて、本番環境とテストの時のように場面に応じて実装を切り替える 設計のパターンのこと
Pubsub もしくは Publish-Subscribe JavaScript モジュールの関係を疎結合にたもつ手法のこと。詳しくは こちら
Functional Programming Wikipedia によると、関数型言語によるプログラミング、もしくは関数型言語を参考したプログラミングのこと
Functional JavaScript 可読性や保守性を目的に関数型言語を参考にした JavaScript プログラミングのこと。または underscore.js や lodash.js を用いたプログラミングのこと。詳しくは こちら
FlowType もしくは Flow JavaScript 用の静的な型判定器のこと。以前は flowtype.org だったようですが、現在は flow.org に変更されています
Redux 主に React の状態を管理するコンテナ a predictable state container のこと
Flux application architecture の一種
Vue.js React や AngularJS と同じ JavaScript Framework の一種
Breaking Change 破壊的変更のこと。例えば React Router v3 → v4 や AngularJS v1 → v2 といった変更のこと
最新の JavaScript 情報の入手経路
Echo JS
Twitter で英語圏の開発者をフォローする
0 notes
Link
The best article ever about monoids. And here are the next two parts:
https://fsharpforfunandprofit.com/posts/monoids-part2/
https://fsharpforfunandprofit.com/posts/monoids-part3/
0 notes
Text
Javascript at server side (part I)
Many of us have in some way used Javascript inside a browser. We know what the DOM is, how to use CSS selectors to operate on DOM elements using JQuery and how to manage Ajax requests. That's the standard stack at the client side of web applications throughout the first decade of 21th century. But with the arise of cloud computing, SaaS and big data challenges we are rethinking the way we code at both client and server side. Regarding server side, asynchronous server architectures driven by the Reactor Pattern have become a must have in order to achieve systems able to scale out and remain responsive to global audiences.
We have several alternatives at server side to achieve that goal. It's a non trivial issue to make a decision on one of them. At the time of this writing a very popular one is node.js. Node.js is a [V8](http://en.wikipedia.org/wiki/V8_(JavaScript_engine) Javascript runtime that implements the reactor pattern. Today we are going to start a series of posts about how to adapt our Javascript (client targeted) knowledge to the server side in order to implement maintainable, clean code for node.js. I assume you already have used Javascript at client side. If you have done so but you are not a Javscript Jedi, nor you have it crystal clear how to use it at server side this series of posts are for you.
Introduction to functions
Javascript is a dynamic, functional featured language. Therefore functions are a core part of it. Our first stop will be trying to gain a deep understanding of what a function is in Javascript. Good resources for this topic are detailed at the end of this post.
Functions as a first class citizens
Functions are a core construct in Javascript. As any other type, they can be defined and invoked anywhere, and passed around as parameters to other functions. We might have also have functions inside other functions:
function foo() { function sqr(n) { return n * n; } return sqr(9); } foo();//81
Function declarations
We declare functions with a name:
//A function called foo function foo() { //Some code here }
An we can invoke them writing () after them or invoking call() on them:
//Both execute foo function foo(); foo.call();
The scope of a function declaration is it's own and the parent (where the function itself is defined).
Function expressions
Function expressions are functions as part of a larger expression. It can be for example a variable assignment or a parameter passed into another function.
//A function inside a variable declaration which refer to the function itself var square = function(x) { return x * x; }; //A function as a parameter to the foo function foo(function(){ /* Some code here */ });
The above showed functions are call anonymous functions because they don't have a name. A function expression could carry a non anonymous function as well.
var foo = function bar() { //Code here };
In case we have a named function in an expression assigned to a variable the function will only be referable through the variable. It's name attribute will be the name of the function.
var foo = function bar() { return 10; }; foo();//returns 10 bar();//ReferenceError: bar is not defined foo.name;//returns 'bar'
The name attribute of an anonymous function is an empty string.
var foo2 = function() { return 100; } foo2.name;//returns ''
The scope of function expressions is the same as variables. Take a look at the next section for details.
Declaration Vs. evaluation
This is an important concept in functional programming. When an expression is declared (or defined) it's not evaluated yet. Only gets evaluated when invoked.
//Declaration of a function expression var sqr = function(x) { return x * x; } //The above defined functions has not been executed yet //Evaluation of the expression sqr(2);//returns 4
Functions can be used either as input or output in other functions
Yes; we can pass a function as a parameter to another function (as we have seen before) or even return a function within another function:
var sqr_function = function() { var actual_function = function(x) { return x * x; } return actual_function; } sqr_function()(3);//Returns 9
Ok, this is a pointless example, but you get the idea, right?
Scoping of variables in Javascript
An important feature of Javascript functions is that they are the only construct in the language allowed to delimitate scopes for variables. In Java and C family languages we can limit an scope with any code block. In Javascript only functions create a new scope. But, contrary to for example Java, it allows us to declare the same variable in the same scope or a nested one without error. See these examples taken from here:
var x = 1; console.log(x); // 1 if (true) { var x = 2; console.log(x); // 2 } console.log(x); // 2
function foo() { var x = 1; if (x) { (function () { var x = 2; // some other code }());//This is a nested self calling function } // x is still 1. }
As you can see a workaround to create a scope inside a function is to create a nested self calling function.
This kind of variable overriding is possible due to the use of the var reserved word. It's the way to define a local variable in Javascript (local to the current scope, that as we have mentioned can be only defined by functions). If we want to define global variables (global to the current scope) we just declare them without the var keyword.
var local = "I'm local"; global = "And I'm global";
Let's see some examples of local and global use of variables in different scopes:
var foo = function() {//Outer scope var x = 5; var bar = function() {//Inner scope var x = 10; return x; } bar(); return x;//returns 5; the second x variable is in another scope }
var foo = function() {//Outer scope var x = 5; var bar = function() {//Inner scope var x = 10; return x; } return bar();//returns 10 }
var foo = function() {//Outer scope x = 5; var bar = function() {//Inner scope x = 10; return x; } bar(); return x;//returns 10; the x is global, so function bar() changes it's value }
var foo = function() {//Outer scope var x = 5; var bar = function() {//Inner scope var y = 10; return x; } bar(); return y;//ReferenceError: y is not defined. Local variables defined with var are not //visible outside their scope (here, the function expression assigned to bar //variable) }
What's next
In the next post of this series I'll get into objects in Javascript and how to adopt an object oriented paradigm.
Resources
Function declarations vs. function expressions.
Javascript scoping and hoisting.
Javascript basics.
0 notes
Link
ZIO is a cutting-edge framework for creating cloud-native JVM applications. Thanks to its user-friendly yet strong functional core, ZIO enables developers to construct best-practice applications that are highly scalable, tested, robust, resilient, resource-safe, efficient, and observable. In this article, we will learn how to develop Event Driven Application using ZIO Actors
0 notes
Link
SoftwareMill, a top-tier software consultancy, joins VirtusLab Group, a leading global provider of IT technology. This merger is part of VirtusLab's strategy of building diverse and independently operating companies to expand its service offerings and become a dominant digital transformation company. As SoftwareMill, we will continue to operate independently, retaining our brand, culture, structure, and values while benefiting from being part of a greater entity: VirtusLab Group.
0 notes
Link
The GHC team is happy to announce the availability of the first (and likely final) release candidate of GHC 9.6.1. As usual, binaries and source distributions are available at downloads.haskell.org. Beginning with GHC 9.6.1, GHC can be built as a cross-compiler to WebAssembly and JavaScript. This is an important step towards robust support for compiling Haskell to the Web, but there are a few caveats to be aware of in the 9.6 series.
0 notes
Link
OCaml is still an excellent programming language for several reasons. It is a high-level, statically typed, functional language, which makes it well-suited for applications that need to be both efficient and reliable. It is also a strongly typed language, making it easier to write safe and more maintainable code. Additionally, OCaml is an open-source language well-supported by a large community. Finally, OCaml features a powerful module system that allows code reuse and makes it easier to build larger applications from smaller components. In this article, you can read six interesting reasons that make OCaml Programming Language a good choice for business.
0 notes
Link
This week’s issue contains some of the most interesting articles and news, selected from all the content published in the previous week on the Developers News website. You will read about Higher-Order Function, Passwordless deployments, Angular 15, GraphQL Federation, PHP version stats, Thymeleaf and Spring Boot, and more
#devs_news_weekly#devs_news#php#angular#GraphQL#Thymeleaf#spring_boot#functional_programming#nodejs#deno#security
0 notes
Link
Higher-Order Functions in functional programming allow developers to create more concise and efficient code by passing functions as arguments to other functions and returning functions as values from other functions. This helps developers to create more modular and reusable code that can be easily extended and maintained over time. Higher-Order Functions also help developers avoid manual iteration and reduce the need for complex control flow logic. Read this article to get familiar with this important concept in functional programming.
0 notes