diff --git a/contributing.md b/contributing.md index a04a54a..138a49a 100644 --- a/contributing.md +++ b/contributing.md @@ -1,7 +1,29 @@ -# Berkontribusi +# Contributing -Proyek ini berkembang seiring dengan berkembangnya konten dari -[_Functional Programming Jargon_](https://github.com/hemanth/functional-programming-jargon/) -milik [hemanth](https://github.com/hemanth/). Maka dari itu sebaiknya Anda -berkontribusi langsung ke _repository_ tersebut. Akan tetapi, kontribusi dalam -bentuk apapun ke _repository_ ini sangat dipersilakan. +This project is a work in progress. Contributions are very welcome. + +## Hard rules +* Run `npm test` to lint the code examples. Your changes must pass. +* If you add a new definition or reorder them run `npm run toc` to regenerate the table of contents. + +That said, we'd like to maintain some consistency across the document. + +## Style guide +1. Every definition should include at least one JavaScript code example. +1. Definitions should be written using the simplest language possible. Every word should tell. +1. Target programmers that have no functional programming experience. +1. We value understandability more than accuracy. e.g. It's okay to describe a functor as a container. +1. Don't overuse jargon even if defined elsewhere in the document. +1. Link to terms defined in the document when you use them in a definition. +1. Avoid big walls of text + +## Code conventions +[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +* Be consistent with other examples +* Prefer arrow functions +* Parenthesis around function arguments +* Put output values in comments +* Keep it short and simple + +This styleguide is a WIP too! Send PRs :) diff --git a/package.json b/package.json index 0379bbc..e7cfe68 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { - "name": "jargon-pemrograman-fungsional", + "name": "functional-programming-jargons", "version": "1.0.0", - "description": "Jargon dari dunia pemrograman fungsional secara sederhana!", + "description": "Jargon from the functional programming world in simple terms!", "main": "index.js", "scripts": { "test": "eslint readme.md", @@ -9,14 +9,14 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/wisn/jargon-pemrograman-fungsional.git" + "url": "git+https://github.com/hemanth/functional-programming-jargon.git" }, - "author": "wisn", + "author": "hemanth", "license": "MIT", "bugs": { - "url": "https://github.com/wisn/jargon-pemrograman-fungsional/issues" + "url": "https://github.com/hemanth/functional-programming-jargon/issues" }, - "homepage": "https://github.com/wisn/jargon-pemrograman-fungsional#readme", + "homepage": "https://github.com/hemanth/functional-programming-jargon#readme", "devDependencies": { "eslint": "^3.4.0", "eslint-config-standard": "^6.0.0", diff --git a/readme.md b/readme.md index 126080e..44c46ce 100644 --- a/readme.md +++ b/readme.md @@ -1,24 +1,20 @@ -# Jargon Pemrograman Fungsional +# Functional Programming Jargon -_Functional programming_ (FP) atau pemrograman fungsional memberikan banyak -keuntungan, dan kini popularitasnya telah meningkat sebagai hasilnya. Namun, -setiap paradigma pemrograman datang dengan jargon uniknya masing-masing -dan FP tidak terkecuali. Dengan memberikan glosarium, -kami berharap dapat mempermudah belajar FP. +Functional programming (FP) provides many advantages, and its popularity has been increasing as a result. However, each programming paradigm comes with its own unique jargon and FP is no exception. By providing a glossary, we hope to make learning FP easier. -Contoh yang ada disajikan dalam JavaScript (ES2015). -[Kenapa JavaScript?](https://github.com/hemanth/functional-programming-jargon/wiki/Why-JavaScript%3F) +Examples are presented in JavaScript (ES2015). [Why JavaScript?](https://github.com/hemanth/functional-programming-jargon/wiki/Why-JavaScript%3F) -*Ini adalah sebuah -[WIP](https://github.com/hemanth/functional-programming-jargon/issues/20) -dari -[Functional Programming Jargon](https://github.com/hemanth/functional-programming-jargon/) -milik [hemanth](https://github.com/hemanth/); Jangan ragu untuk mengirim PR ;)* +*This is a [WIP](https://github.com/hemanth/functional-programming-jargon/issues/20); please feel free to send a PR ;)* -Jika ada, dokumen ini menggunakan istilah yang didefinisikan dalam spesifikasi -[Fantasy Land](https://github.com/fantasyland/fantasy-land). +Where applicable, this document uses terms defined in the [Fantasy Land spec](https://github.com/fantasyland/fantasy-land) -__Daftar Isi__ +__Translations__ +* [Portuguese](https://github.com/alexmoreno/jargoes-programacao-funcional) +* [Spanish](https://github.com/idcmardelplata/functional-programming-jargon/tree/master) +* [Chinese](https://github.com/shfshanyue/fp-jargon-zh) +* [Bahasa Indonesia](https://github.com/wisn/jargon-pemrograman-fungsional) + +__Table of Contents__ * [Arity](#arity) @@ -30,11 +26,11 @@ __Daftar Isi__ * [Function Composition](#function-composition) * [Continuation](#continuation) * [Purity](#purity) -* [Side Effect](#side-effects) +* [Side effects](#side-effects) * [Idempotent](#idempotent) * [Point-Free Style](#point-free-style) * [Predicate](#predicate) -* [Contract](#contract) +* [Contracts](#contracts) * [Category](#category) * [Value](#value) * [Constant](#constant) @@ -56,29 +52,19 @@ __Daftar Isi__ * [Setoid](#setoid) * [Semigroup](#semigroup) * [Foldable](#foldable) -* [Type Signature](#type-signature) +* [Type Signatures](#type-signatures) * [Algebraic data type](#algebraic-data-type) * [Sum type](#sum-type) * [Product type](#product-type) * [Option](#option) -* [Pustaka Pemrograman Fungsional dalam JavaScript](#pustaka-pemrograman-fungsional-dalam-javascript) +* [Functional Programming Libraries in JavaScript](#functional-programming-libraries-in-javascript) ## Arity -_Arity_ merupakan banyaknya argumen yang diambil oleh fungsi. -Berasal dari kata-kata seperti _unary_, _binary_, _ternary_, dan lain-lain. -Kata ini memiliki perbedaan yang terdiri dari dua sufiks, "-ary" dan "-ity." -Penjumlahan, misalnya, mengambil dua argumen, dan jadi didefinisikan sebagai -fungsi biner (_binary function_) atau fungsi dengan dua _arity_. -Fungsi semacam itu terkadang disebut "_dyadic_" oleh orang-orang yang lebih -menyukai bahasa Yunani dari bahasa Latin. -Demikian juga, fungsi yang mengambil sejumlah variabel argumen disebut -"_variadic_", sedangkan fungsi biner harus diberikan dua dan hanya dua -argumen, meskipun _currying_ dan _partial application_ (lihat di bawah). - +The number of arguments a function takes. From words like unary, binary, ternary, etc. This word has the distinction of being composed of two suffixes, "-ary" and "-ity." Addition, for example, takes two arguments, and so it is defined as a binary function or a function with an arity of two. Such a function may sometimes be called "dyadic" by people who prefer Greek roots to Latin. Likewise, a function that takes a variable number of arguments is called "variadic," whereas a binary function must be given two and only two arguments, currying and partial application notwithstanding (see below). ```js const sum = (a, b) => a + b @@ -86,14 +72,12 @@ const sum = (a, b) => a + b const arity = sum.length console.log(arity) // 2 -// Arity dari fungsi `sum` adalah dua +// The arity of sum is 2 ``` ## Higher-Order Functions (HOF) -_Higher-Order Function_ adalah sebuah fungsi yang mengambil fungsi sebagai -argumen dan/atau mengembalikan sebuah fungsi. - +A function which takes a function as an argument and/or returns a function. ```js const filter = (predicate, xs) => xs.filter(predicate) @@ -109,50 +93,40 @@ filter(is(Number), [0, '1', 2, null]) // [0, 2] ## Partial Application -Menerapkan fungsi secara parsial (_Partial Application_ atau Fungsi Parsial) -artinya membuat fungsi baru dengan mengisi beberapa argumen ke fungsi semula. +Partially applying a function means creating a new function by pre-filling some of the arguments to the original function. ```js -// Helper membuat sebagian fungsi yang diaplikasikan -// Mengambil sebuah fungsi dan beberapa argumen +// Helper to create partially applied functions +// Takes a function and some arguments const partial = (f, ...args) => - // mengembalikan sebuah fungsi yang mengambil sisa argumen + // returns a function that takes the rest of the arguments (...moreArgs) => - // dan memanggil fungsi asilnya dengan semuanya + // and calls the original function with all of them f(...args, ...moreArgs) -// Sesuatu untuk diaplikasikan +// Something to apply const add3 = (a, b, c) => a + b + c -// Menerapkan `2` dan `3` secara parsial ke `add3` -// Sehingga, memberikan Anda sebuah fungsi dengan satu argumen +// Partially applying `2` and `3` to `add3` gives you a one-argument function const fivePlus = partial(add3, 2, 3) // (c) => 2 + 3 + c fivePlus(4) // 9 ``` -Anda juga dapat menggunakan `Function.prototype.bind` untuk menerapkan -fungsi parsial di JavaScript: - +You can also use `Function.prototype.bind` to partially apply a function in JS: ```js const add1More = add3.bind(null, 2, 3) // (c) => 2 + 3 + c ``` -_Partial application_ atau fungsi parsial membantu menciptakan fungsi yang -lebih sederhana dari yang lebih kompleks dengan memadukan data saat Anda -memilikinya. [_Curried_](#currying) _function_ sudah secara otomatis diterapkan -secara parsial. +Partial application helps create simpler functions from more complex ones by baking in data when you have it. [Curried](#currying) functions are automatically partially applied. ## Currying -_Currying_ merupakan sebuah proses mengubah fungsi yang membutuhkan banyak -argumen menjadi fungsi yang membawa mereka satu-persatu. - -Setiap kali fungsi dipanggil hanya menerima satu argumen dan mengembalikan -sebuah fungsi yang membutuhkan satu argumen sampai semua argumen dilewatkan. +The process of converting a function that takes multiple arguments into a function that takes them one at a time. +Each time the function is called it only accepts one argument and returns a function that takes one argument until all arguments are passed. ```js const sum = (a, b) => a + b @@ -169,66 +143,39 @@ add2(10) // 12 ## Closure -_Closure_ merupakan sebuah cara untuk mengakses sebuah variabel yang berada -di luar cakupannya. -Secara formal, _closure_ merupakan sebuah teknik untuk menerapkan _lexically -scoped_ bernama _binding_. Ini adalah cara untuk menyimpan sebuah fungsi -dengan sebuah _environment_. +A closure is a way of accessing a variable outside its scope. +Formally, a closure is a technique for implementing lexically scoped named binding. It is a way of storing a function with an environment. -_Closure_ adalah lingkup yang menangkap variabel lokal dari suatu fungsi untuk -askes bahkan setelah eksekusi telah berpindah dari blok yang didefinisikan. -Yaitu, mereka membiarkan referensi lingkup setelah blok dimana variabel -dinyatakan telah selesai mengeksekusi. +A closure is a scope which captures local variables of a function for access even after the execution has moved out of the block in which it is defined. +ie. they allow referencing a scope after the block in which the variables were declared has finished executing. ```js const addTo = x => y => x + y var addToFive = addTo(5) -addToFive(3) // mengembalikan 8 +addToFive(3) // returns 8 ``` +The function ```addTo()``` returns a function(internally called ```add()```), lets store it in a variable called ```addToFive``` with a curried call having parameter 5. -Fungsi `addTo()` mengembalikan sebuah fungsi (secara internal disebut `add()`), -lalu disimpan di variabel yang disebut `addToFive` dengan _curried call_ yang -memiliki parameter `5`. +Ideally, when the function ```addTo``` finishes execution, its scope, with local variables add, x, y should not be accessible. But, it returns 8 on calling ```addToFive()```. This means that the state of the function ```addTo``` is saved even after the block of code has finished executing, otherwise there is no way of knowing that ```addTo``` was called as ```addTo(5)``` and the value of x was set to 5. -Idealnya, ketika fungsi `addTo` selesai dieksekusi, cakupannya, -dengan variabel lokal `add`, `x`, `y` seharusnya tidak dapat diakses. Tapi, -itu mengembalikan `8` ketika memanggil `addToFive()`. Ini artinya kondisi -dari fungsi `addTo` disimpan bahkan setelah blok kode selesai dieksekusi. -Jika tidak, tidak mungkin dapat mengetahui bahwa `addTo` telah dipanggil -sebagai `addTo(5)` dan nilai dari `x` telah ditentukan menjadi `5`. +Lexical scoping is the reason why it is able to find the values of x and add - the private variables of the parent which has finished executing. This value is called a Closure. -_Lexical scoping_ adalah alasan mengapa ia dapat menemukan nilai dari `x` dan -`add` - sebuah variabel _private_ induk yang telah selesai dieksekusi. -Nilai ini disebut _Closure_. +The stack along with the lexical scope of the function is stored in form of reference to the parent. This prevents the closure and the underlying variables from being garbage collected(since there is at least one live reference to it). -`Stack` beserta `lexical scope` fungsinya disimpan dalam bentuk referensi -ke induknya. Hal ini mencegah _closure_ dan variabel-variabel mendasar agar -tidak dikumpulkan sebagai sampah (karena setidaknya ada satu refernsi -langsung untuk itu). +Lambda Vs Closure: A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects. -__Lambda Vs. Closure__ -_Lambda_ pada dasarnya adalah fungsi yang didefinisikan secara _inline_ -daripada metode standar untuk mendeklarasikan fungsi. Lambda sering dapat -dilewatkan sebagai objek. - -_Closure_ adalah fungsi yang membungkus keadaan sekitarnya dengan -mereferensikan bidang yang ada di luar tubuhnya. _State_ tertutup tetap -berada di seberang seruan _closure_. +A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure. -__Bacaan lebih lanjut/Sumber__ +__Further reading/Sources__ * [Lambda Vs Closure](http://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda) * [How do JavaScript Closures Work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) ## Auto Currying +Transforming a function that takes multiple arguments into one that if given less than its correct number of arguments returns a function that takes the rest. When the function gets the correct number of arguments it is then evaluated. -_Auto currying_ mengubah fungsi yang membutuhkan banyak argumen menjadi -argumen yang jika diberikan kurang dari jumlah argumen yang benar mengembalikan -sebuah fungsi yang mengambil sisanya. Bila fungsi mendapatkan jumlah argumen -yang benar, maka akan dievaluasi. - -lodash dan Ramda memiliki fungsi `curry` yang bekerja seperti di bawah. +lodash & Ramda have a `curry` function that works this way. ```js const add = (x, y) => x + y @@ -239,28 +186,23 @@ curriedAdd(1) // (y) => 1 + y curriedAdd(1)(2) // 3 ``` -__Bacaan lebih lanjut__ +__Further reading__ * [Favoring Curry](http://fr.umio.us/favoring-curry/) * [Hey Underscore, You're Doing It Wrong!](https://www.youtube.com/watch?v=m3svKOdZijA) ## Function Composition -_Function composition_ atau komposisi fungsi adalah tindakan yang menempatkan -dua fungsi bersama untuk membentuk fungsi ketiga dimana keluaran dari satu -fungsi adalah masukan dari yang lain. - +The act of putting two functions together to form a third function where the output of one function is the input of the other. ```js -const compose = (f, g) => (a) => f(g(a)) // Definisi -const floorAndToString = compose((val) => val.toString(), Math.floor) // Penggunaan +const compose = (f, g) => (a) => f(g(a)) // Definition +const floorAndToString = compose((val) => val.toString(), Math.floor) // Usage floorAndToString(121.212121) // '121' ``` ## Continuation -Pada suatu titik dalam sebuah program, bagian dari kode yang belum dieksekusi -dikenal sebagai kelanjutan/kontinuitas atau _continuation_. - +At any given point in a program, the part of the code that's yet to be executed is known as a continuation. ```js const printAsString = (num) => console.log(`Given ${num}`) @@ -273,20 +215,16 @@ const addOneAndContinue = (num, cc) => { addOneAndContinue(2, printAsString) // 'Given 3' ``` -Kontinuitas sering terlihat pada pemrograman _asynchronous_ saat program -perlu menunggu untuk menerima data sebelum dapat melanjutkan. Responnya -sering dilewatkan ke sisa program, yang merupakan kelanjutannya, begitu -sudah diterima. - +Continuations are often seen in asynchronous programming when the program needs to wait to receive data before it can continue. The response is often passed off to the rest of the program, which is the continuation, once it's been received. ```js const continueProgramWith = (data) => { - // Melanjutkan program dengan data + // Continues program with data } readFileAsync('path/to/file', (err, response) => { if (err) { - // mengatasi galat + // handle error return } continueProgramWith(response) @@ -295,10 +233,8 @@ readFileAsync('path/to/file', (err, response) => { ## Purity -Sebuah fungsi dikatan murni atau _pure_ jika mengembalikan nilai yang hanya -ditentukan oleh nilai masukannya, dan tidak menghasilkan efek samping -atau _side effect_. - +A function is pure if the return value is only determined by its +input values, and does not produce side effects. ```js const greet = (name) => `Hi, ${name}` @@ -306,8 +242,7 @@ const greet = (name) => `Hi, ${name}` greet('Brianne') // 'Hi, Brianne' ``` -Berbeda dengan masing-masing hal di bawah: - +As opposed to each of the following: ```js window.name = 'Brianne' @@ -317,8 +252,7 @@ const greet = () => `Hi, ${window.name}` greet() // "Hi, Brianne" ``` -Contoh keluaran di atas didasarkan pada data yang tersimpan di luar fungsi... - +The above example's output is based on data stored outside of the function... ```js let greeting @@ -331,14 +265,11 @@ greet('Brianne') greeting // "Hi, Brianne" ``` -... dan yang satu ini memodifikasi keadaan di luar fungsi. +... and this one modifies state outside of the function. -## Side Effect - -Sebuah fungsi atau ekspresi dikatakan memiliki efek samping jika selain -mengembalikan nilai, ia berinterasksi dengan (membaca dari atau menulis ke) -keadaan yang dapat berubah eksternal. +## Side effects +A function or expression is said to have a side effect if apart from returning a value, it interacts with (reads from or writes to) external mutable state. ```js const differentEveryTime = new Date() @@ -350,9 +281,7 @@ console.log('IO is a side effect!') ## Idempotent -Suatu fungsi _idempotent_ jika mengaplikasikannya kembali hasilnya tidak -menghasilkan hasil yang berbeda. - +A function is idempotent if reapplying it to its result does not produce a different result. ``` f(f(x)) ≍ f(x) @@ -368,40 +297,28 @@ sort(sort(sort([2, 1]))) ## Point-Free Style -Menulis fungsi dimana definisi tidak secara eksplisit mengidentifikasi -argumen yang digunakan. Gaya ini biasanya memerlukan [_currying_](#currying) -atau lainnya [_Higher-Order function_](#higher-order-functions-hof). -Alias, _Tacit programming_. - +Writing functions where the definition does not explicitly identify the arguments used. This style usually requires [currying](#currying) or other [Higher-Order functions](#higher-order-functions-hof). A.K.A Tacit programming. ```js -// Diberikan +// Given const map = (fn) => (list) => list.map(fn) const add = (a) => (b) => a + b -// Lalu +// Then -// Bukan points-free - `numbers` merupakan argumen eksplisit +// Not points-free - `numbers` is an explicit argument const incrementAll = (numbers) => map(add(1))(numbers) -// Points-free - `list` merupakan argumen implisit +// Points-free - The list is an implicit argument const incrementAll2 = map(add(1)) ``` -`incrementAll` mengidentifikasi dan menggunakan parameter `numbers`, jadi itu -bukan _points-free_. `incrementAll2` dituliskan hanya dengan menggabungkan -beberapa fungsi dan beberapa nilai, membuatnya tidak menyebut satu pun -argumennya. Itu __adalah__ _points-free_. +`incrementAll` identifies and uses the parameter `numbers`, so it is not points-free. `incrementAll2` is written just by combining functions and values, making no mention of its arguments. It __is__ points-free. -Definisi _points-free function_ terlihat seperti _assignment_ normal tanpa -`function` atau `=>`. +Points-free function definitions look just like normal assignments without `function` or `=>`. ## Predicate - -Suatu _predicate_ adalah sebuah fungsi yang mengembalikan nilai `true` atau -`false` untuk suatu nilai yang diberikan. Biasanya digunakan sebagai _callback_ -untuk menyaring _array_. - +A predicate is a function that returns true or false for a given value. A common use of a predicate is as the callback for array filter. ```js const predicate = (a) => a > 2 @@ -409,16 +326,12 @@ const predicate = (a) => a > 2 ;[1, 2, 3, 4].filter(predicate) // [3, 4] ``` -## Contract - -Suatu _contract_ menentukan kewajiban dan jaminan perilaku dari suatu fungsi -atau ekspresi saat _runtime_. Ini bertindak sebagai seperangkat aturan yang -diharapkan dari masukan dan keluaran suatu fungsi atau ekspresi, dan -kesalahan umumnya dilaporkan setiap kali sebuah kontrak dilanggar. +## Contracts +A contract specifies the obligations and guarantees of the behavior from a function or expression at runtime. This acts as a set of rules that are expected from the input and output of a function or expression, and errors are generally reported whenever a contract is violated. ```js -// Mendefinisikan contract kami : int -> int +// Define our contract : int -> int const contract = (input) => { if (typeof input === 'number') return true throw new Error('Contract violated: expected int -> int') @@ -432,34 +345,30 @@ addOne('some string') // Contract violated: expected int -> int ## Category -Kategori dalam _category theory_ adalah kumpulan objek dan morfisme -(_morphism_) di antara keduanya. Dalam pemrograman, biasanya _types_ bertindak -sebagai objek dan fungsi sebagai morfisme. +A category in category theory is a collection of objects and morphisms between them. In programming, typically types +act as the objects and functions as morphisms. +To be a valid category 3 rules must be met: -Untuk menjadi kategori yang sah, tiga aturan harus dipenuhi: +1. There must be an identity morphism that maps an object to itself. + Where `a` is an object in some category, + there must be a function from `a -> a`. +2. Morphisms must compose. + Where `a`, `b`, and `c` are objects in some category, + and `f` is a morphism from `a -> b`, and `g` is a morphism from `b -> c`; + `g(f(x))` must be equivalent to `(g • f)(x)`. +3. Composition must be associative + `f • (g • h)` is the same as `(f • g) • h` -1. Harus ada morfisme identitas yang memetakan objek itu sendiri. - Dimana `a` adalah sebuah objek dalam beberapa kategori, - harus ada fungsi dari `a -> a`. -2. Morfisme harus disusun. - Dimana `a`, `b`, dan `c` adalah objek dalam beberapa kategori, - dan `f` adalah morfisme dari `a -> b`, serta `g` adalah morfisme dari - `b -> c`; `g(f(x))` harus sama dengan `(g • f)(x)`. -3. Komposisi harus asosiatif. - `f • (g • h)` sama halnya dengan `(f • g) • h`. +Since these rules govern composition at very abstract level, category theory is great at uncovering new ways of composing things. -Karena aturan ini mengatur komposisi pada tingkat yang sangat abstrak, -teori kategori sangat bagus dalam menemukan cara baru untuk menyusun sesuatu. - -__Bacaan lebih lanjut__ +__Further reading__ * [Category Theory for Programmers](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/) ## Value -Apa saja yang dapat di-_assign_ ke variabel. - +Anything that can be assigned to a variable. ```js 5 @@ -471,20 +380,16 @@ undefined ## Constant -Sebuah variabel yang tidak dapat ditetapkan kembali setelah ditentukan nilainya. +A variable that cannot be reassigned once defined. ```js const five = 5 const john = Object.freeze({name: 'John', age: 30}) ``` -_Constant_ atau konstanta adalah -[_referentially transparent_](#referential-transparency). Artinya, mereka -dapat diganti dengan nilai yang mereka wakili tanpa mempengaruhi hasilnya. - -Dengan dua konstanta di atas, ekspresi berikut akan selalu mengembalikan -nilai `true`. +Constants are [referentially transparent](#referential-transparency). That is, they can be replaced with the values that they represent without affecting the result. +With the above two constants the following expression will always return `true`. ```js john.age + five === ({name: 'John', age: 30}).age + (5) @@ -492,10 +397,7 @@ john.age + five === ({name: 'John', age: 30}).age + (5) ## Functor -Suatu objek yang mengimplementasikan fungsi `map`, yang ketika menjalankan -lebih dari setiap nilai pada objek untuk menghasilkan objek baru, mematuhi -dua aturan: - +An object that implements a `map` function which, while running over each value in the object to produce a new object, adheres to two rules: __Preserves identity__ ``` @@ -508,18 +410,15 @@ __Composable__ object.map(compose(f, g)) ≍ object.map(g).map(f) ``` -(`f`, `g` menjadi fungsi sewenang-wenang) - -_Functor_ umum dalam JavaScript adalah `Array` karena mematuhi dua aturan -_functor_, yaitu: +(`f`, `g` be arbitrary functions) +A common functor in JavaScript is `Array` since it abides to the two functor rules: ```js [1, 2, 3].map(x => x) // = [1, 2, 3] ``` -dan - +and ```js const f = x => x + 1 @@ -530,12 +429,9 @@ const g = x => x * 2 ``` ## Pointed Functor +An object with an `of` function that puts _any_ single value into it. -Suatu objek dengan sebuah fungsi `of` yang mengambil _semua_ nilai tunggal -ke dalamnya. - -ES2015 menambahkan `Array.of` yang menjadikannya _pointed functor_. - +ES2015 adds `Array.of` making arrays a pointed functor. ```js Array.of(1) // [1] @@ -543,30 +439,22 @@ Array.of(1) // [1] ## Lift -_Lifting_ atau mengangkat (dari kata _lift_, angkat) adalah saat Anda -mengambil sebuah nilai dan mengambilnya ke dalam suatu objek seperti -[functor](#pointed-functor). Jika Anda mengangkat sebuah fungsi ke dalam -[Applicative Functor](#applicative-functor), maka Anda dapat membuatnya -bekerja pada nilai-nilai yang juga ada di _functor_ itu. - -Beberapa implementasi memiliki fungsi yang disebut `lift`, atau `liftA2` agar -lebih mudah menjalankan fungsi pada _functor_. +Lifting is when you take a value and put it into an object like a [functor](#pointed-functor). If you lift a function into an [Applicative Functor](#applicative-functor) then you can make it work on values that are also in that functor. +Some implementations have a function called `lift`, or `liftA2` to make it easier to run functions on functors. ```js -const liftA2 = (f) => (a, b) => a.map(f).ap(b) // catatan: itu `ap`, bukan `map`. +const liftA2 = (f) => (a, b) => a.map(f).ap(b) // note it's `ap` and not `map`. const mult = a => b => a * b -const liftedMult = liftA2(mult) // fungsi ini sekarang bekerja pada functor seperti array +const liftedMult = liftA2(mult) // this function now works on functors like array liftedMult([1, 2], [3]) // [3, 6] liftA2(a => b => a + b)([1, 2], [3, 4]) // [4, 5, 5, 6] ``` -Mengangkat fungsi satu argumen dan menerapkannya melakukan hal yang sama -seperti `map`. - +Lifting a one-argument function and applying it does the same thing as `map`. ```js const increment = (x) => x + 1 @@ -575,30 +463,28 @@ lift(increment)([2]) // [3] ;[2].map(increment) // [3] ``` + ## Referential Transparency -Sebuah ekspresi yang dapat diganti nilainya dengan tanpa mengubah tingkah laku -program tersebut dikatan _referentially_ transparan. - -Katakanlah kita memiliki fungsi `greet`: +An expression that can be replaced with its value without changing the +behavior of the program is said to be referentially transparent. +Say we have function greet: ```js const greet = () => 'Hello World!' ``` -Setiap seruan dari `greet()` dapat ditimpa dengan `Hello World!`, karena itu -`greet` secara referensial transparan. +Any invocation of `greet()` can be replaced with `Hello World!` hence greet is +referentially transparent. ## Equational Reasoning -Ketika sebuah aplikasi terdiri dari ekspresi dan tanpa efek samping, -kebenaran tentang sistem dapat diturunkan dari bagian-bagiannya. +When an application is composed of expressions and devoid of side effects, truths about the system can be derived from the parts. ## Lambda -Fungsi anonim yang dapat diperlakukan seperti sebuah nilai. - +An anonymous function that can be treated like a value. ```js ;(function (a) { @@ -607,33 +493,24 @@ Fungsi anonim yang dapat diperlakukan seperti sebuah nilai. ;(a) => a + 1 ``` - -_Lambda_ juga sering dilewatkan sebagai argumen ke _Higher-Order function_. - +Lambdas are often passed as arguments to Higher-Order functions. ```js [1, 2].map((a) => a + 1) // [2, 3] ``` -Anda dapat menugaskan (_assign_) suatu _lambda_ ke dalam sebuah variabel. - +You can assign a lambda to a variable. ```js const add1 = (a) => a + 1 ``` ## Lambda Calculus - -Sebuah cabang dari matematika yang menggunakan fungsi untuk membuat suatu -[model universal dari komputasi](https://en.wikipedia.org/wiki/Lambda_calculus). +A branch of mathematics that uses functions to create a [universal model of computation](https://en.wikipedia.org/wiki/Lambda_calculus). ## Lazy evaluation -_Lazy evaluation_ adalah mekanisme evaluasi panggilan-per-kebutuhan yang -menunda evaluasi suatu ekspresi sampai nilainya dibutuhkan. Dalam bahasa -fungsional, ini memungkinkan struktur seperti _infinite list_, yang biasanya -tidak tersedia dalam bahasa imperatif dimana urutan perintah sangat penting. - +Lazy evaluation is a call-by-need evaluation mechanism that delays the evaluation of an expression until its value is needed. In functional languages, this allows for structures like infinite lists, which would not normally be available in an imperative language where the sequencing of commands is significant. ```js const rand = function*() { @@ -645,97 +522,79 @@ const rand = function*() { ```js const randIter = rand() -randIter.next() // Setiap eksekusi memberikan nilai acak, ekspresi dievaluasi hanya saat dibutuhkan +randIter.next() // Each execution gives a random value, expression is evaluated on need. ``` ## Monoid -Objek dengan fungsi yang "menggabungkan" objek itu sendiri dengan tipe lain -yang sama. - -Salah satu _monoid_ sederhana adalah penjumlahan angka: +An object with a function that "combines" that object with another of the same type. +One simple monoid is the addition of numbers: ```js 1 + 1 // 2 ``` +In this case number is the object and `+` is the function. -Dalam kasus ini, angka adalah objek dan `+` adalah fungsi. - -Nilai "identitas" juga harus ada bila dikombinasikan dengan nilai yang tidak -mengubahnya. - -Nilai identitas untuk penjumlahan adalah `0`. - +An "identity" value must also exist that when combined with a value doesn't change it. +The identity value for addition is `0`. ```js 1 + 0 // 1 ``` -Ini juga memerlukan pengelompokkan operasi yang tidak akan mempengaruhi -hasilnya (asosiatif): - +It's also required that the grouping of operations will not affect the result (associativity): ```js 1 + (2 + 3) === (1 + 2) + 3 // true ``` -Rangkaian _array_ juga membentuk _monoid_: - +Array concatenation also forms a monoid: ```js ;[1, 2].concat([3, 4]) // [1, 2, 3, 4] ``` -Nilai identitasnya adalah _array_ kosong atau `[]`. - +The identity value is empty array `[]` ```js ;[1, 2].concat([]) // [1, 2] ``` -Jika fungsi identitas dan komposisi disediakan, maka fungsinya membentuk monoid: - +If identity and compose functions are provided, functions themselves form a monoid: ```js const identity = (a) => a const compose = (f, g) => (x) => f(g(x)) ``` - -`foo` adalah fungsi apapun yang mengambil satu argumen. - - +`foo` is any function that takes one argument. ``` compose(foo, identity) ≍ compose(identity, foo) ≍ foo ``` ## Monad -_Monad_ adalah sebuah objek dengan fungsi [`of`](#pointed-functor) dan `chain`. -`chain` ini seperti [`map`](#functor), kecuali itu "membatalkan" objek -bersarang yang dihasilkan. - +A monad is an object with [`of`](#pointed-functor) and `chain` functions. `chain` is like [`map`](#functor) except it un-nests the resulting nested object. ```js -// Implementasi +// Implementation Array.prototype.chain = function (f) { return this.reduce((acc, it) => acc.concat(f(it)), []) } -// Penggunaan +// Usage ;Array.of('cat,dog', 'fish,bird').chain((a) => a.split(',')) // ['cat', 'dog', 'fish', 'bird'] -// Kontras ke map +// Contrast to map ;Array.of('cat,dog', 'fish,bird').map((a) => a.split(',')) // [['cat', 'dog'], ['fish', 'bird']] ``` -`of` juga diketahui sebagai `return` di bahasa fungsional lainnya. -`chain` juga diketahui sebagai `flatmap` dan `bind` di bahasa lainnya. +`of` is also known as `return` in other functional languages. +`chain` is also known as `flatmap` and `bind` in other languages. ## Comonad -Suatu objek yang memiliki fungsi `extract` dan `extend`. - +An object that has `extract` and `extend` functions. ```js const CoIdentity = (v) => ({ @@ -749,16 +608,13 @@ const CoIdentity = (v) => ({ }) ``` -`extract` mengambil sebuah nilai keluar dari _functor_. - +Extract takes a value out of a functor. ```js CoIdentity(1).extract() // 1 ``` -_extend_ menjalankan fungsi di atas _comonad_. Fungsi tersebut seharusnya -mengembalikan tipe yang sama dengan _comonad_. - +Extend runs a function on the comonad. The function should return the same type as the comonad. ```js CoIdentity(1).extend((co) => co.extract() + 1) // CoIdentity(2) @@ -766,38 +622,32 @@ CoIdentity(1).extend((co) => co.extract() + 1) // CoIdentity(2) ## Applicative Functor -Suatu _applicative functor_ adalah sebuah objek dengan fungsi `ap`. `ap` -menerapkan fungsi pada objek ke nilai objek lain dari tipe yang sama. - +An applicative functor is an object with an `ap` function. `ap` applies a function in the object to a value in another object of the same type. ```js -// Implementasi +// Implementation Array.prototype.ap = function (xs) { return this.reduce((acc, f) => acc.concat(xs.map(f)), []) } -// Contoh penggunaan +// Example usage ;[(a) => a + 1].ap([1]) // [2] ``` -Ini berguna jika Anda memiliki dua objek dan Anda ingin menerapkan fungsi biner -ke isinya. - +This is useful if you have two objects and you want to apply a binary function to their contents. ```js -// Array yang ingin digabungkan +// Arrays that you want to combine const arg1 = [1, 3] const arg2 = [4, 5] -// menggabungkan fungsi - harus curried untuk pekerjaan ini +// combining function - must be curried for this to work const add = (x) => (y) => x + y const partiallyAppliedAdds = [add].ap(arg1) // [(y) => 1 + y, (y) => 3 + y] ``` -Ini memberi Anda sebuah _array_ dari sejumlah fungsi yang dapat Anda sebut `ap` -untuk mendapatkan hasilnya: - +This gives you an array of functions that you can call `ap` on to get the result: ```js partiallyAppliedAdds.ap(arg2) // [5, 6, 7, 8] @@ -805,12 +655,11 @@ partiallyAppliedAdds.ap(arg2) // [5, 6, 7, 8] ## Morphism -Sebuah fungsi transformasi. +A transformation function. ### Endomorphism -Sebuah fungsi dimana tipe masukannya sama dengan keluarannya. - +A function where the input type is the same as the output. ```js // uppercase :: String -> String @@ -822,15 +671,12 @@ const decrement = (x) => x - 1 ### Isomorphism -Sepasang transformasi antara dua jenis benda yang bersifat struktural dan tidak -ada data yang hilang. - -Sebagai contoh, koordinat 2D dapat disimpan sebagai _array_ `[2, 3]` atau objek -`{x: 2, y: 3}`. +A pair of transformations between 2 types of objects that is structural in nature and no data is lost. +For example, 2D coordinates could be stored as an array `[2,3]` or object `{x: 2, y: 3}`. ```js -// Menyediakan fungsi untuk mengubah kedua arah membuat mereka isomorfik +// Providing functions to convert in both directions makes them isomorphic. const pairToCoords = (pair) => ({x: pair[0], y: pair[1]}) const coordsToPair = (coords) => [coords.x, coords.y] @@ -840,13 +686,13 @@ coordsToPair(pairToCoords([1, 2])) // [1, 2] pairToCoords(coordsToPair({x: 1, y: 2})) // {x: 1, y: 2} ``` + + ## Setoid -Suatu objek yang memiliki fungsi `equals` yang mana dapat digunakan untuk -membandingkan objek lain dengan tipe yang sama. - -Menjadikan _array_ suatu _setoid_: +An object that has an `equals` function which can be used to compare other objects of the same type. +Make array a setoid: ```js Array.prototype.equals = function (arr) { @@ -868,9 +714,7 @@ Array.prototype.equals = function (arr) { ## Semigroup -Suatu objek yang memiliki fungsi `concat` yang menggabungkannya dengan objek -lain dengan tipe yang sama. - +An object that has a `concat` function that combines it with another object of the same type. ```js ;[1].concat([2]) // [1, 2] @@ -878,23 +722,18 @@ lain dengan tipe yang sama. ## Foldable -Suatu objek yang memiliki fungsi `reduce` yang dapat mengubah objek tersebut -menjadi tipe yang lain. - +An object that has a `reduce` function that can transform that object into some other type. ```js const sum = (list) => list.reduce((acc, val) => acc + val, 0) sum([1, 2, 3]) // 6 ``` -## Type Signature +## Type Signatures -Seringkali fungsi dalam JavaScript memiliki komentar yang menunjukkan tipe dari -argumen dan nilai pengembaliannya. - -Ada sedikit perbedaan di antara komunitas/masyarakat, namun mereka sering -mengikuti pola berikut: +Often functions in JavaScript will include comments that indicate the types of their arguments and return values. +There's quite a bit of variance across the community but they often follow the following patterns: ```js // functionName :: firstArgType -> secondArgType -> returnType @@ -906,95 +745,66 @@ const add = (x) => (y) => x + y const increment = (x) => x + 1 ``` -Jika suatu fungsi menerima fungsi lain sebagai argumennya, maka itu dibungkus -dengan tanda kurung. - +If a function accepts another function as an argument it is wrapped in parentheses. ```js // call :: (a -> b) -> a -> b const call = (f) => (x) => f(x) ``` -Huruf `a`, `b`, `c`, `d` digunakan sebagai tanda bahwa argumen tersebut dapat -berbentuk apa saja. Layaknya versi dari `map`, mengambil sebuah fungsi -yang mengubah nilai dari bentuk `a` ke bentuk lain `b`, sebuah _array_ dengan -nilai berbentuk `a`, dan mengembalikan sebuah _array_ dengan nilai berbentuk -`b`. - +The letters `a`, `b`, `c`, `d` are used to signify that the argument can be of any type. The following version of `map` takes a function that transforms a value of some type `a` into another type `b`, an array of values of type `a`, and returns an array of values of type `b`. ```js // map :: (a -> b) -> [a] -> [b] const map = (f) => (list) => list.map(f) ``` -__Bacan lebih lanjut__ +__Further reading__ * [Ramda's type signatures](https://github.com/ramda/ramda/wiki/Type-Signatures) * [Mostly Adequate Guide](https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch7.html#whats-your-type) -* [What is Hindley-Milner?](http://stackoverflow.com/a/399392/22425) di Stack Overflow +* [What is Hindley-Milner?](http://stackoverflow.com/a/399392/22425) on Stack Overflow ## Algebraic data type - -Jenis komposit yang dibuat dari jenis lainnya. Dua kelas umum dari tipe aljabar -(_algebraic type_) adalah [_sum_](#sum-type) dan [_product_](#product-type). +A composite type made from putting other types together. Two common classes of algebraic types are [sum](#sum-type) and [product](#product-type). ### Sum type +A Sum type is the combination of two types together into another one. It is called sum because the number of possible values in the result type is the sum of the input types. -_Sum type_ adalah kombinasi dari dua _type_ menjadi satu sama lain. Ini disebut -jumlah (_sum_) karena jumlah nilai yang mungkin terjadi pada _type_ hasil -adalah jumlah dari tipe masukan. - -JavaScript tidak memiliki _type_ seperti ini, tapi kita dapat menggunakan `Set` -untuk berpura-pura: - - +JavaScript doesn't have types like this but we can use `Set`s to pretend: ```js -// bayangkan bahwa daripada Set di sini kita memiliki tipe yang hanya memiliki nilai-nilai ini +// imagine that rather than sets here we have types that can only have these values const bools = new Set([true, false]) const halfTrue = new Set(['half-true']) -// Tipe `weakLogic` mengandung jumlah nilai dari `bools` dan `halfTrue` +// The weakLogic type contains the sum of the values from bools and halfTrue const weakLogicValues = new Set([...bools, ...halfTrue]) ``` -_Sum type_ terkadang disebut _union type_, _discriminated union_, atau _tagged -union_. +Sum types are sometimes called union types, discriminated unions, or tagged unions. -Ada [beberapa](https://github.com/paldepind/union-type) -[pustaka](https://github.com/puffnfresh/daggy) dalam JavaScript yang -membantu mendefinisikan dan menggunakan _union type_. +There's a [couple](https://github.com/paldepind/union-type) [libraries](https://github.com/puffnfresh/daggy) in JS which help with defining and using union types. -_Flow_ memasukkan [_union type_](https://flow.org/en/docs/types/unions/) dan -TypeScript memiliki -[Enums](https://www.typescriptlang.org/docs/handbook/enums.html) untuk melayani -peran yang sama. +Flow includes [union types](https://flow.org/en/docs/types/unions/) and TypeScript has [Enums](https://www.typescriptlang.org/docs/handbook/enums.html) to serve the same role. ### Product type -Tipe ***product*** menggabungkan beberapa tipe bersama, dengan cara yang mungkin -Anda telah akrab: +A **product** type combines types together in a way you're probably more familiar with: ```js // point :: (Number, Number) -> {x: Number, y: Number} const point = (x, y) => ({x: x, y: y}) ``` +It's called a product because the total possible values of the data structure is the product of the different values. Many languages have a tuple type which is the simplest formulation of a product type. -Ini disebut produk (_product_) karena nilai total dari struktur data adalah -produk dari nilai yang berbeda. Banyak bahasa memiliki tipe _tuple_ yang -merupakan formulasi sederhana dari _product type_. - -Lihat juga [teori himpunan](https://id.wikipedia.org/wiki/Teori_himpunan). +See also [Set theory](https://en.wikipedia.org/wiki/Set_theory). ## Option +Option is a [sum type](#sum-type) with two cases often called `Some` and `None`. -_Option_ adalah suatu _[sum type](#sum-type)_ dengan dua kasus yang sering -disebut `Some` dan `None`. - -_Option_ sangat berguna untuk menyusun fungsi-fungsi yang mungkin tidak -mengembalikan sebuah nilai. - +Option is useful for composing functions that might not return a value. ```js -// Definisi naif +// Naive definition const Some = (v) => ({ val: v, @@ -1018,10 +828,7 @@ const None = () => ({ // maybeProp :: (String, {a}) -> Option a const maybeProp = (key, obj) => typeof obj[key] === 'undefined' ? None() : Some(obj[key]) ``` - -Gunakan `chain` untuk mengurutkan fungsi yang mengembalikan `Option`. - - +Use `chain` to sequence functions that return `Option`s ```js // getItem :: Cart -> Option CartItem @@ -1038,10 +845,9 @@ getNestedPrice({item: {foo: 1}}) // None() getNestedPrice({item: {price: 9.99}}) // Some(9.99) ``` -`Option` juga dikenal sebagai `Maybe`. `Some` terkadang disebut `Just`. -`None` terkadang disebut `Nothing`. +`Option` is also known as `Maybe`. `Some` is sometimes called `Just`. `None` is sometimes called `Nothing`. -## Pustaka Pemrograman Fungsional dalam JavaScript +## Functional Programming Libraries in JavaScript * [mori](https://github.com/swannodette/mori) * [Immutable](https://github.com/facebook/immutable-js/) @@ -1054,11 +860,8 @@ getNestedPrice({item: {price: 9.99}}) // Some(9.99) * [Lazy.js](https://github.com/dtao/lazy.js) * [maryamyriameliamurphies.js](https://github.com/sjsyrek/maryamyriameliamurphies.js) * [Haskell in ES6](https://github.com/casualjavascript/haskell-in-es6) +* [Sanctuary](https://github.com/sanctuary-js/sanctuary) --- -__P.S:__ _Repository_ ini di-_fork_ dari proyek -[_Functional Programming Jargon_](https://github.com/hemanth/functional-programming-jargon/) -milik [hemanth](https://github.com/hemanth/) dan telah dikatakan berhasil karena -[kontribusi](https://github.com/hemanth/functional-programming-jargon/graphs/contributors) -yang luar biasa. +__P.S:__ This repo is successful due to the wonderful [contributions](https://github.com/hemanth/functional-programming-jargon/graphs/contributors)!