From 6909259fbd08b7c220d0db46c145f47363af085a Mon Sep 17 00:00:00 2001 From: sockmaster27 <61235930+sockmaster27@users.noreply.github.com> Date: Sun, 5 Nov 2023 16:11:34 +0100 Subject: [PATCH 1/2] chore: add Prettier configuration --- .github/workflows/code-checks.yml | 15 +++++++++++++++ .prettierignore | 3 +++ .prettierrc | 11 +++++++++++ .vscode/extensions.json | 7 +++++++ .vscode/settings.json | 11 +++++++++++ 5 files changed, 47 insertions(+) create mode 100644 .github/workflows/code-checks.yml create mode 100644 .prettierignore create mode 100644 .prettierrc create mode 100644 .vscode/extensions.json create mode 100644 .vscode/settings.json diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml new file mode 100644 index 0000000..44d88d9 --- /dev/null +++ b/.github/workflows/code-checks.yml @@ -0,0 +1,15 @@ +name: Code Style + +on: + push: + branches: [master] + pull_request: + branches: [master] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Check code formatting + run: npx prettier . --check diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..d8ffa7d --- /dev/null +++ b/.prettierignore @@ -0,0 +1,3 @@ +node_modules/** +build/** +src/data/** diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..67ac7dc --- /dev/null +++ b/.prettierrc @@ -0,0 +1,11 @@ +{ + "printWidth": 120, + "tabWidth": 2, + "semi": false, + "singleQuote": true, + "quoteProps": "as-needed", + "trailingComma": "all", + "bracketSpacing": true, + "arrowParens": "avoid", + "endOfLine": "auto" +} diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..b1eeca3 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations. + // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp + + // List of extensions which should be recommended for users of this workspace. + "recommendations": ["esbenp.prettier-vscode"] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..f25bd2e --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,11 @@ +{ + "json.schemaDownload.enable": true, + "eslint.enable": true, + "editor.codeActionsOnSave": { + "source.fixAll.eslint": true + }, + "editor.detectIndentation": false, + "editor.formatOnSave": true, + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.tabSize": 2 +} From e5799c6884c528ac38c3d90bec7bcdcd6392fe61 Mon Sep 17 00:00:00 2001 From: sockmaster27 <61235930+sockmaster27@users.noreply.github.com> Date: Sun, 5 Nov 2023 16:15:03 +0100 Subject: [PATCH 2/2] chore: run formatting on all files --- .github/workflows/node.js.yml | 7 +- AUTHORS.md | 2 +- LICENSE.md | 11 +- build-scripts/main.mjs | 34 +- build-scripts/sampleFiles.mjs | 230 ++-- public/index.html | 41 +- src/App.css | 81 +- src/App.js | 284 +++-- src/index.js | 20 +- src/page/About.js | 560 ++++----- src/page/Blog.js | 165 ++- src/page/Contribute.js | 161 ++- src/page/Documentation.js | 263 ++-- src/page/Faq.js | 1215 ++++++++---------- src/page/GetStarted.js | 132 +- src/page/Home.js | 1259 +++++++++---------- src/page/Internships.js | 113 +- src/page/Koans.js | 165 ++- src/page/Principles.js | 1173 ++++++++--------- src/page/Research.js | 311 ++--- src/page/blog/DesignFlaws.js | 545 ++++---- src/page/blog/Naming.js | 696 +++++----- src/page/blog/PolymorphicEffects.js | 1037 +++++++-------- src/page/blog/ProgrammingLanguageDefense.js | 651 +++++----- src/page/blog/Redundancies.js | 630 ++++------ src/page/misc/Checklist.js | 44 +- src/util/Codebox.js | 222 ++-- src/util/Editor.js | 52 +- src/util/FlixMode.js | 139 +- src/util/InlineEditor.js | 77 +- 30 files changed, 4922 insertions(+), 5398 deletions(-) diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index 226cd3f..077ab46 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -5,13 +5,12 @@ name: Node.js CI on: push: - branches: [ master ] + branches: [master] pull_request: - branches: [ master ] + branches: [master] jobs: build: - runs-on: ubuntu-latest strategy: @@ -26,4 +25,4 @@ jobs: with: node-version: ${{ matrix.node-version }} - run: npm ci - - run: npm run build --if-present \ No newline at end of file + - run: npm run build --if-present diff --git a/AUTHORS.md b/AUTHORS.md index f9ca241..3984e90 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -1,5 +1,5 @@ # Contributors By adding your name to this document, you agree to release all your contributions to Flix under the [Apache 2.0 License](LICENSE.md). - + - [Magnus Madsen](https://github.com/magnus-madsen) diff --git a/LICENSE.md b/LICENSE.md index 1cf109f..5312f82 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,5 +1,4 @@ -Apache License -============== +# Apache License _Version 2.0, January 2004_ _<<http://www.apache.org/licenses/>>_ @@ -89,15 +88,15 @@ You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: -* **(a)** You must give any other recipients of the Work or Derivative Works a copy of +- **(a)** You must give any other recipients of the Work or Derivative Works a copy of this License; and -* **(b)** You must cause any modified files to carry prominent notices stating that You +- **(b)** You must cause any modified files to carry prominent notices stating that You changed the files; and -* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, +- **(c)** You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and -* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any +- **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the diff --git a/build-scripts/main.mjs b/build-scripts/main.mjs index cfc2751..0de5ad8 100644 --- a/build-scripts/main.mjs +++ b/build-scripts/main.mjs @@ -1,29 +1,29 @@ -import fs from "fs"; +import fs from 'fs' -import { sampleFiles, baseUrl } from "./sampleFiles.mjs"; +import { sampleFiles, baseUrl } from './sampleFiles.mjs' async function fetchSamples(baseUrl, files) { - return await Promise.all( - files.map(async sample => { - const response = await fetch(baseUrl + sample.file); - const code = await response.text(); + return await Promise.all( + files.map(async sample => { + const response = await fetch(baseUrl + sample.file) + const code = await response.text() - return { - name: sample.name, - code, - }; - }) - ); + return { + name: sample.name, + code, + } + }), + ) } -const samples = await fetchSamples(baseUrl, sampleFiles); -const objString = JSON.stringify(samples); +const samples = await fetchSamples(baseUrl, sampleFiles) +const objString = JSON.stringify(samples) const fileString = ` // This file is generated by build-scripts/main.mjs /* eslint-disable */ export default ${objString}; -`; +` // The file is placed in the src directory to include it in the bundle -fs.mkdirSync("./src/data", { recursive: true }); -fs.writeFileSync("./src/data/Samples.js", fileString); +fs.mkdirSync('./src/data', { recursive: true }) +fs.writeFileSync('./src/data/Samples.js', fileString) diff --git a/build-scripts/sampleFiles.mjs b/build-scripts/sampleFiles.mjs index d851765..ea9a48d 100644 --- a/build-scripts/sampleFiles.mjs +++ b/build-scripts/sampleFiles.mjs @@ -1,116 +1,116 @@ -const version = "0.38.0"; -export const baseUrl = `https://raw.githubusercontent.com/flix/flix/v${version}/examples/`; +const version = '0.38.0' +export const baseUrl = `https://raw.githubusercontent.com/flix/flix/v${version}/examples/` export const sampleFiles = [ - { - name: "Algebraic Data Types and Pattern Matching", - file: "algebraic-data-types-and-pattern-matching.flix", - }, - { - name: "Lists and List Processing", - file: "lists-and-list-processing.flix", - }, - { - name: "Higher-Order Functions", - file: "higher-order-functions.flix", - }, - { - name: "Enums and Parametric Polymorphism", - file: "enums-and-parametric-polymorphism.flix", - }, - { - name: "Record Construction and Use", - file: "record-construction-and-use.flix", - }, - { - name: "Polymorphic Record Update", - file: "polymorphic-record-update.flix", - }, - { - name: "Polymorphic Record Extension and Restriction", - file: "polymorphic-record-extension-and-restriction.flix", - }, - { - name: "Function Composition, Pipelines, and Currying", - file: "function-composition-pipelines-and-currying.flix", - }, - { - name: "Pure and Impure Functions", - file: "pure-and-impure-functions.flix", - }, - { - name: "Effect Polymorphic Functions", - file: "effect-polymorphic-functions.flix", - }, - { - name: "Type Aliases", - file: "type-aliases.flix", - }, - { - name: "Mutual Recursion with Full Tail-Call Elimination", - file: "mutual-recursion-with-full-tail-call-elimination.flix", - }, - { - name: "Sending and Receiving on Channels", - file: "sending-and-receiving-on-channels.flix", - }, - { - name: "Using Channels and Select", - file: "using-channels-and-select.flix", - }, - { - name: "Select with Defaults and Timers", - file: "select-with-defaults-and-timers.flix", - }, - { - name: "First-Class Constraints and Fixpoints", - file: "first-class-constraints-and-fixpoints.flix", - }, - { - name: "Polymorphic First-Class Constraints", - file: "polymorphic-first-class-constraints.flix", - }, - { - name: "Pipelines of Fixpoint Computations", - file: "pipelines-of-fixpoint-computations.flix", - }, - { - name: "Using Datalog to Solve a Compiler Puzzle", - file: "compiler-puzzle.flix", - }, - { - name: "An Interpreter for a Trivial Expression Language", - file: "an-interpreter-for-a-trivial-expression-language.flix", - }, - { - name: "A Simple Card Game Simulation", - file: "simple-card-game.flix", - }, - { - name: "Deriving Type Classes", - file: "deriving-type-classes.flix", - }, - { - name: "Internal Mutability with Regions", - file: "internal-mutability-with-regions.flix", - }, - { - name: "File Information", - file: "file-information.flix", - }, - { - name: "Working with Files and Directories", - file: "working-with-files-and-directories.flix", - }, - { - name: "Using Laziness for Infinite Streams", - file: "using-laziness-for-infinite-streams.flix", - }, - { - name: "Using Laziness for Logging", - file: "using-laziness-for-logging.flix", - }, - { - name: "Using Laziness to Compute Fibonacci", - file: "using-laziness-to-compute-fibonacci.flix", - } -]; \ No newline at end of file + { + name: 'Algebraic Data Types and Pattern Matching', + file: 'algebraic-data-types-and-pattern-matching.flix', + }, + { + name: 'Lists and List Processing', + file: 'lists-and-list-processing.flix', + }, + { + name: 'Higher-Order Functions', + file: 'higher-order-functions.flix', + }, + { + name: 'Enums and Parametric Polymorphism', + file: 'enums-and-parametric-polymorphism.flix', + }, + { + name: 'Record Construction and Use', + file: 'record-construction-and-use.flix', + }, + { + name: 'Polymorphic Record Update', + file: 'polymorphic-record-update.flix', + }, + { + name: 'Polymorphic Record Extension and Restriction', + file: 'polymorphic-record-extension-and-restriction.flix', + }, + { + name: 'Function Composition, Pipelines, and Currying', + file: 'function-composition-pipelines-and-currying.flix', + }, + { + name: 'Pure and Impure Functions', + file: 'pure-and-impure-functions.flix', + }, + { + name: 'Effect Polymorphic Functions', + file: 'effect-polymorphic-functions.flix', + }, + { + name: 'Type Aliases', + file: 'type-aliases.flix', + }, + { + name: 'Mutual Recursion with Full Tail-Call Elimination', + file: 'mutual-recursion-with-full-tail-call-elimination.flix', + }, + { + name: 'Sending and Receiving on Channels', + file: 'sending-and-receiving-on-channels.flix', + }, + { + name: 'Using Channels and Select', + file: 'using-channels-and-select.flix', + }, + { + name: 'Select with Defaults and Timers', + file: 'select-with-defaults-and-timers.flix', + }, + { + name: 'First-Class Constraints and Fixpoints', + file: 'first-class-constraints-and-fixpoints.flix', + }, + { + name: 'Polymorphic First-Class Constraints', + file: 'polymorphic-first-class-constraints.flix', + }, + { + name: 'Pipelines of Fixpoint Computations', + file: 'pipelines-of-fixpoint-computations.flix', + }, + { + name: 'Using Datalog to Solve a Compiler Puzzle', + file: 'compiler-puzzle.flix', + }, + { + name: 'An Interpreter for a Trivial Expression Language', + file: 'an-interpreter-for-a-trivial-expression-language.flix', + }, + { + name: 'A Simple Card Game Simulation', + file: 'simple-card-game.flix', + }, + { + name: 'Deriving Type Classes', + file: 'deriving-type-classes.flix', + }, + { + name: 'Internal Mutability with Regions', + file: 'internal-mutability-with-regions.flix', + }, + { + name: 'File Information', + file: 'file-information.flix', + }, + { + name: 'Working with Files and Directories', + file: 'working-with-files-and-directories.flix', + }, + { + name: 'Using Laziness for Infinite Streams', + file: 'using-laziness-for-infinite-streams.flix', + }, + { + name: 'Using Laziness for Logging', + file: 'using-laziness-for-logging.flix', + }, + { + name: 'Using Laziness to Compute Fibonacci', + file: 'using-laziness-to-compute-fibonacci.flix', + }, +] diff --git a/public/index.html b/public/index.html index 9348685..06085b7 100644 --- a/public/index.html +++ b/public/index.html @@ -1,26 +1,29 @@ -<!DOCTYPE html> +<!-- Whether 'doctype' should be upper- or lowercase seems to be controversial and inconsistent across Prettier versions --> +<!-- prettier-ignore --> +<!doctype html> + <html lang="en"> -<head> - <meta charset="utf-8"> - <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> - <meta name="theme-color" content="#000000"> - <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> + <meta name="theme-color" content="#000000" /> + <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" /> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <title>Flix | The Flix Programming Language</title> -</head> -<body> -<noscript> - You need to enable JavaScript to run this app. -</noscript> + </head> + <body> + <noscript> You need to enable JavaScript to run this app. </noscript> -<a href="https://github.com/flix/flix"> - <img style="position: absolute; top: 0; right: 0; border: 0; z-index: 9999;" - src="https://github.blog/wp-content/uploads/2008/12/forkme_right_green_007200.png" - alt="Fork me on GitHub"> -</a> + <a href="https://github.com/flix/flix"> + <img + style="position: absolute; top: 0; right: 0; border: 0; z-index: 9999" + src="https://github.blog/wp-content/uploads/2008/12/forkme_right_green_007200.png" + alt="Fork me on GitHub" + /> + </a> -<div id="root"></div> -<!-- + <div id="root"></div> + <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page. @@ -30,5 +33,5 @@ To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> -</body> + </body> </html> diff --git a/src/App.css b/src/App.css index ae387ec..cb25a79 100644 --- a/src/App.css +++ b/src/App.css @@ -1,96 +1,97 @@ body { - font-family: 'Open Sans', sans-serif; - overflow-y: scroll; + font-family: 'Open Sans', sans-serif; + overflow-y: scroll; - background-color: #efefef; + background-color: #efefef; } h1 { - font-size: 2rem; - margin-bottom: 0.75rem; - text-align: left; + font-size: 2rem; + margin-bottom: 0.75rem; + text-align: left; } h2 { - font-size: 1.7rem; - margin-bottom: 0.75rem; - text-align: left; + font-size: 1.7rem; + margin-bottom: 0.75rem; + text-align: left; } h3 { - font-size: 1.6rem; - margin-bottom: 0.75rem; - text-align: left; + font-size: 1.6rem; + margin-bottom: 0.75rem; + text-align: left; } p:last-child { - margin-bottom: 0; + margin-bottom: 0; } .menu { - margin-left: -15px; - margin-right: -15px; + margin-left: -15px; + margin-right: -15px; } .page { - background-color: white; - min-height: 95vh; + background-color: white; + min-height: 95vh; } .motto { - font-size: 1.35rem; - color: #17a2b8; + font-size: 1.35rem; + color: #17a2b8; } .editor-output h5 { - font-size: 1.1rem; - color: gray; - text-align: center; - padding-bottom: 0.5rem; - border-bottom: 1px solid #b7b7b7; + font-size: 1.1rem; + color: gray; + text-align: center; + padding-bottom: 0.5rem; + border-bottom: 1px solid #b7b7b7; } .editor-output pre { - font-family: monospace; + font-family: monospace; } .inline-editor-frame { - margin-top: 1em; - margin-bottom: 1.5em; + margin-top: 1em; + margin-bottom: 1.5em; } .inline-editor-code { - padding: 1em 1.5em; - background-color: #f7f7f7; + padding: 1em 1.5em; + background-color: #f7f7f7; } .nav-item { - cursor: pointer; + cursor: pointer; } .navbar-nav .nav-item .nav-link { - color: rgba(255, 255, 255, .85) + color: rgba(255, 255, 255, 0.85); } .navbar-nav .nav-item .nav-link:hover { - color: rgba(255, 255, 255, 1.00) + color: rgba(255, 255, 255, 1); } -.btn-group .btn, .btn-xs { - padding: .1rem .5rem; - font-size: .875rem; - line-height: 1.5; - border-radius: .2rem; +.btn-group .btn, +.btn-xs { + padding: 0.1rem 0.5rem; + font-size: 0.875rem; + line-height: 1.5; + border-radius: 0.2rem; } .card-title { - font-size: 1.2rem; + font-size: 1.2rem; } .ace_hidden-cursors { - opacity: 0 + opacity: 0; } .w-33 { - width: 33%; + width: 33%; } diff --git a/src/App.js b/src/App.js index b7f9453..cf5496b 100644 --- a/src/App.js +++ b/src/App.js @@ -1,152 +1,168 @@ -import React, {Component} from 'react'; -import './App.css'; - -import Home from "./page/Home"; -import GetStarted from "./page/GetStarted"; -import Documentation from "./page/Documentation"; -import Principles from "./page/Principles"; -import Contribute from "./page/Contribute"; -import Research from "./page/Research"; -import Faq from "./page/Faq"; -import Checklist from "./page/misc/Checklist"; -import {Container, Navbar, Nav, NavItem, NavLink, Row} from 'reactstrap'; -import {Route} from "react-router"; -import {Link} from "react-router-dom"; - -import ReconnectingWebSocket from 'reconnecting-websocket'; -import About from "./page/About"; -import Blog from "./page/Blog"; -import Koans from "./page/Koans"; -import Internships from "./page/Internships"; - -const SocketAddress = 'wss://evaluator.flix.dev/ws'; +import React, { Component } from 'react' +import './App.css' + +import Home from './page/Home' +import GetStarted from './page/GetStarted' +import Documentation from './page/Documentation' +import Principles from './page/Principles' +import Contribute from './page/Contribute' +import Research from './page/Research' +import Faq from './page/Faq' +import Checklist from './page/misc/Checklist' +import { Container, Navbar, Nav, NavItem, NavLink, Row } from 'reactstrap' +import { Route } from 'react-router' +import { Link } from 'react-router-dom' + +import ReconnectingWebSocket from 'reconnecting-websocket' +import About from './page/About' +import Blog from './page/Blog' +import Koans from './page/Koans' +import Internships from './page/Internships' + +const SocketAddress = 'wss://evaluator.flix.dev/ws' class App extends Component { - constructor(props) { - super(props); - - this.state = { - connected: false - }; - - console.log("Connecting to: " + SocketAddress); - - let options = { - connectionTimeout: 2500 - }; - - this.websocket = new ReconnectingWebSocket(SocketAddress, [], options); - - this.websocket.addEventListener("open", event => { - console.log("Connected to: " + SocketAddress); - this.setState({connected: true}); - }); - this.websocket.addEventListener("close", event => { - console.log("Disconnected from: " + SocketAddress); - console.log(event); - this.setState({connected: false}); - }); - this.websocket.addEventListener("error", event => { - console.log("Disconnected from: " + SocketAddress); - console.log(event); - this.setState({connected: false}); - }); - } + constructor(props) { + super(props) - runProgram = (src, callback) => { - if (!this.state.connected) { - console.log("Not connected yet"); - return; - } + this.state = { + connected: false, + } - this.websocket.onmessage = event => { - console.log("Received reply from: " + SocketAddress); - const data = JSON.parse(event.data); + console.log('Connecting to: ' + SocketAddress) - console.log(data); - callback(data); - }; + let options = { + connectionTimeout: 2500, + } - let data = { - src: src - }; + this.websocket = new ReconnectingWebSocket(SocketAddress, [], options) + + this.websocket.addEventListener('open', event => { + console.log('Connected to: ' + SocketAddress) + this.setState({ connected: true }) + }) + this.websocket.addEventListener('close', event => { + console.log('Disconnected from: ' + SocketAddress) + console.log(event) + this.setState({ connected: false }) + }) + this.websocket.addEventListener('error', event => { + console.log('Disconnected from: ' + SocketAddress) + console.log(event) + this.setState({ connected: false }) + }) + } + + runProgram = (src, callback) => { + if (!this.state.connected) { + console.log('Not connected yet') + return + } - this.websocket.send(JSON.stringify(data)); - }; + this.websocket.onmessage = event => { + console.log('Received reply from: ' + SocketAddress) + const data = JSON.parse(event.data) - getHome() { - return <Home flix={{connected: this.state.connected, run: this.runProgram.bind(this)}}/> + console.log(data) + callback(data) } - render() { - return ( - <Container className="page"> - <Navbar dark color="info" expand="md" className="menu shadow-sm mb-4"> - <Nav className="mr-lg-auto" navbar> - <NavItem className="pl-1 pr-1"> - <NavLink tag={Link} to="/">Home</NavLink> - </NavItem> + let data = { + src: src, + } - {/* + this.websocket.send(JSON.stringify(data)) + } + + getHome() { + return <Home flix={{ connected: this.state.connected, run: this.runProgram.bind(this) }} /> + } + + render() { + return ( + <Container className="page"> + <Navbar dark color="info" expand="md" className="menu shadow-sm mb-4"> + <Nav className="mr-lg-auto" navbar> + <NavItem className="pl-1 pr-1"> + <NavLink tag={Link} to="/"> + Home + </NavLink> + </NavItem> + + {/* <NavItem className="pl-1 pr-1"> <NavLink tag={Link} to="/about/">About</NavLink> </NavItem> */} - <NavItem className="pl-1 pr-1"> - <NavLink tag={Link} to="/get-started/">Get Started</NavLink> - </NavItem> - - <NavItem className="pl-1 pr-1"> - <NavLink tag={Link} - to="/principles/">Principles</NavLink> - </NavItem> - - <NavItem className="pl-1 pr-1"> - <NavLink tag={Link} to="/documentation/">Documentation</NavLink> - </NavItem> - - <NavItem className="pl-1 pr-1"> - <NavLink tag={Link} to="/research/">Research</NavLink> - </NavItem> - - <NavItem className="pl-1 pr-1"> - <NavLink tag={Link} to="/faq/">FAQ</NavLink> - </NavItem> - - <NavItem className="pl-1 pr-1"> - <NavLink tag={Link} to="/blog/">Blog</NavLink> - </NavItem> - - <NavItem className="pl-1 pr-1"> - <NavLink tag={Link} to="/contribute/">Contribute</NavLink> - </NavItem> - - <NavItem className="pl-1 pr-1"> - <NavLink tag={Link} to="/internships/">Internships</NavLink> - </NavItem> - </Nav> - </Navbar> - - <Route path="/" exact render={() => this.getHome()}/> - <Route path="/about/" component={About}/> - <Route path="/get-started/" component={GetStarted}/> - <Route path="/principles/" component={Principles}/> - <Route path="/documentation/" component={Documentation}/> - <Route path="/research/" component={Research}/> - <Route path="/faq/" component={Faq}/> - <Route path="/blog/" component={Blog}/> - <Route path="/contribute/" component={Contribute}/> - <Route path="/internships/" component={Internships}/> - - <Route path="/misc/checklist/" component={Checklist}/> - <Route path="/misc/koans/" component={Koans}/> - - <Row/> - - </Container> - ); - } + <NavItem className="pl-1 pr-1"> + <NavLink tag={Link} to="/get-started/"> + Get Started + </NavLink> + </NavItem> + + <NavItem className="pl-1 pr-1"> + <NavLink tag={Link} to="/principles/"> + Principles + </NavLink> + </NavItem> + + <NavItem className="pl-1 pr-1"> + <NavLink tag={Link} to="/documentation/"> + Documentation + </NavLink> + </NavItem> + + <NavItem className="pl-1 pr-1"> + <NavLink tag={Link} to="/research/"> + Research + </NavLink> + </NavItem> + + <NavItem className="pl-1 pr-1"> + <NavLink tag={Link} to="/faq/"> + FAQ + </NavLink> + </NavItem> + + <NavItem className="pl-1 pr-1"> + <NavLink tag={Link} to="/blog/"> + Blog + </NavLink> + </NavItem> + + <NavItem className="pl-1 pr-1"> + <NavLink tag={Link} to="/contribute/"> + Contribute + </NavLink> + </NavItem> + + <NavItem className="pl-1 pr-1"> + <NavLink tag={Link} to="/internships/"> + Internships + </NavLink> + </NavItem> + </Nav> + </Navbar> + + <Route path="/" exact render={() => this.getHome()} /> + <Route path="/about/" component={About} /> + <Route path="/get-started/" component={GetStarted} /> + <Route path="/principles/" component={Principles} /> + <Route path="/documentation/" component={Documentation} /> + <Route path="/research/" component={Research} /> + <Route path="/faq/" component={Faq} /> + <Route path="/blog/" component={Blog} /> + <Route path="/contribute/" component={Contribute} /> + <Route path="/internships/" component={Internships} /> + + <Route path="/misc/checklist/" component={Checklist} /> + <Route path="/misc/koans/" component={Koans} /> + + <Row /> + </Container> + ) + } } -export default App; +export default App diff --git a/src/index.js b/src/index.js index dd109f3..9c6a031 100644 --- a/src/index.js +++ b/src/index.js @@ -1,12 +1,12 @@ -import React from 'react'; -import ReactDOM from 'react-dom'; -import 'bootstrap/dist/css/bootstrap.min.css'; -import App from './App'; -import {BrowserRouter} from "react-router-dom"; +import React from 'react' +import ReactDOM from 'react-dom' +import 'bootstrap/dist/css/bootstrap.min.css' +import App from './App' +import { BrowserRouter } from 'react-router-dom' ReactDOM.render( - <BrowserRouter basename="/"> - <App/> - </BrowserRouter>, - document.getElementById('root') -); + <BrowserRouter basename="/"> + <App /> + </BrowserRouter>, + document.getElementById('root'), +) diff --git a/src/page/About.js b/src/page/About.js index 4ae07c7..93571ab 100644 --- a/src/page/About.js +++ b/src/page/About.js @@ -1,66 +1,58 @@ -import React, {Component} from "react"; -import {Col, Container, Row} from "reactstrap"; -import InlineEditor from "../util/InlineEditor"; +import React, { Component } from 'react' +import { Col, Container, Row } from 'reactstrap' +import InlineEditor from '../util/InlineEditor' class About extends Component { + componentDidMount() { + document.title = 'Flix | About' + } - componentDidMount() { - document.title = "Flix | About"; - } - - render() { - return ( - <Container style={{"text-align": "justify"}}> - - <Row className="mb-3"> - <Col sm={12} md={8}> - - <h1>About</h1> - - <p> - Flix is a functional-, logic-, and imperative- programming language focusing on making it - simple to write safe, robust, and elegant programs. It tries to achieve this through a - combination of a strong static type system with type inference, an extensive collection of - compile-time checks, and by - avoiding many of the mistakes of programming languages past. Flix aims to have a principled - design that does <i>not</i> sacrifice safety nor elegance at the altar of expediency. <i>Flix - is a language for programmers that care about programs.</i> - </p> - - <p> - Flix draws inspiration from many other excellent languages, including Elm, F#, OCaml, - Haskell, Rust, and Scala. Flix visually resembles Scala with an emphasis on conciseness and - the use of keywords. We believe that short keywords are a useful visual aid when scanning - through source code and trying to quickly understand its structure. The static type system - of Flix supports (local) type inference and is based on Hindley-Milner like those of OCaml - and Haskell. The concurrency model of Flix is based on channels and processes as known from - Go. Flix aspires to have understandable and detailed error-messages like those found in Elm. - </p> - - <p> - The Flix language and compiler is open source and freely available under the permissive - Apache 2.0 license. - </p> - - <h2>Hello World</h2> - - <p> - The much celebrated hello world program in Flix: - </p> - - <InlineEditor> - {`def main(): Unit \\ IO = + render() { + return ( + <Container style={{ 'text-align': 'justify' }}> + <Row className="mb-3"> + <Col sm={12} md={8}> + <h1>About</h1> + + <p> + Flix is a functional-, logic-, and imperative- programming language focusing on making it simple to write + safe, robust, and elegant programs. It tries to achieve this through a combination of a strong static type + system with type inference, an extensive collection of compile-time checks, and by avoiding many of the + mistakes of programming languages past. Flix aims to have a principled design that does <i>not</i>{' '} + sacrifice safety nor elegance at the altar of expediency.{' '} + <i>Flix is a language for programmers that care about programs.</i> + </p> + + <p> + Flix draws inspiration from many other excellent languages, including Elm, F#, OCaml, Haskell, Rust, and + Scala. Flix visually resembles Scala with an emphasis on conciseness and the use of keywords. We believe + that short keywords are a useful visual aid when scanning through source code and trying to quickly + understand its structure. The static type system of Flix supports (local) type inference and is based on + Hindley-Milner like those of OCaml and Haskell. The concurrency model of Flix is based on channels and + processes as known from Go. Flix aspires to have understandable and detailed error-messages like those + found in Elm. + </p> + + <p> + The Flix language and compiler is open source and freely available under the permissive Apache 2.0 + license. + </p> + + <h2>Hello World</h2> + + <p>The much celebrated hello world program in Flix:</p> + + <InlineEditor> + {`def main(): Unit \\ IO = println("Hello World!")`} - </InlineEditor> + </InlineEditor> - <h2>Basic Functional Programming</h2> + <h2>Basic Functional Programming</h2> - <p> - Flix allows us to define our own data types and use pattern matching to take them apart: - </p> + <p>Flix allows us to define our own data types and use pattern matching to take them apart:</p> - <InlineEditor> - {`/// An algebraic data type for shapes. + <InlineEditor> + {`/// An algebraic data type for shapes. enum Shape { case Circle(Int32), // circle radius case Square(Int32), // side length @@ -77,14 +69,12 @@ def area(s: Shape): Int32 = match s { // Computes the area of a 2 by 4. def main(): Unit \\ IO = area(Rectangle(2, 4)) |> println`} - </InlineEditor> + </InlineEditor> - <p> - Flix supports parametric polymorphism (generics) as the following example shows: - </p> + <p>Flix supports parametric polymorphism (generics) as the following example shows:</p> - <InlineEditor> - {`/// An algebraic data type for binary trees where each leaf carries a value of type a. + <InlineEditor> + {`/// An algebraic data type for binary trees where each leaf carries a value of type a. enum Tree[a] { case Leaf(a), case Node(Tree[a], Tree[a]) @@ -111,28 +101,27 @@ def tree(): Tree[Int32] = Node(Leaf(1), Leaf(2)) /// Squares all elements in the simple tree. def main(): Unit \\ IO = map(x -> x * x, tree()) |> println`} - </InlineEditor> + </InlineEditor> - <p> - Note that type parameters may be omitted from function signatures, as shown in definition - of <code>map</code>. - </p> + <p> + Note that type parameters may be omitted from function signatures, as shown in definition of{' '} + <code>map</code>. + </p> - <h2>Concurrency</h2> + <h2>Concurrency</h2> - <p> - The concurrency model of Flix is inspired by Go. In Flix, processes communicate - via immutable message-passing over channels. - </p> + <p> + The concurrency model of Flix is inspired by Go. In Flix, processes communicate via immutable + message-passing over channels. + </p> - <p> - The following program spawns a new process to perform a (trivial) computation and then sends - the - result to the main process using a channel. - </p> + <p> + The following program spawns a new process to perform a (trivial) computation and then sends the result to + the main process using a channel. + </p> - <InlineEditor> - {`/// Computes the sum of \`x\` and \`y\` and sends the result on the channel \`tx\`. + <InlineEditor> + {`/// Computes the sum of \`x\` and \`y\` and sends the result on the channel \`tx\`. def sum(x: Int32, y: Int32, tx: Sender[Int32, r]): Unit \\ { Write(r) } = Channel.send((x + y), tx) @@ -142,18 +131,16 @@ def main(): Int32 \\ IO = region r { spawn sum(21, 42, tx) @ r; // spawn sum to run in a separate process. Channel.recv(rx) // wait for the result to arrive on the channel. }`} - </InlineEditor> - - <p> - The powerful <code>select</code> expression can be used to choose the first element that - becomes - available from a collection of channels. The select expression can be used to implement many - useful - features, such as load balancing, producer-consumer patterns, and timeouts. - </p> - - <InlineEditor> - {`/// Sends the string \`s\` on the channel \`tx\` up to \`n\` times. + </InlineEditor> + + <p> + The powerful <code>select</code> expression can be used to choose the first element that becomes available + from a collection of channels. The select expression can be used to implement many useful features, such + as load balancing, producer-consumer patterns, and timeouts. + </p> + + <InlineEditor> + {`/// Sends the string \`s\` on the channel \`tx\` up to \`n\` times. def animal(s: String, n: Int32, tx: Sender[String, r]): Unit \\ { Write(r), IO } = match n { case 0 => () @@ -174,104 +161,97 @@ def main(): Unit \\ IO = region r { case hiss <- Channel.recv(rx3) => hiss /// rx3 became ready first } |> println }`} - </InlineEditor> + </InlineEditor> - <h2>Polymorphic Effects: Separating Pure and Impure Code</h2> + <h2>Polymorphic Effects: Separating Pure and Impure Code</h2> - <p> - A unique feature of Flix is its polymorphic effect system. The Flix type and effect system - cleanly separates pure and impure code. If an expression is pure then it always - evaluates to the same value and it cannot have a side-effect. If a function is pure then it - always evaluates to the same value when given the same arguments. - </p> + <p> + A unique feature of Flix is its polymorphic effect system. The Flix type and effect system cleanly + separates pure and impure code. If an expression is pure then it always evaluates to the same value and it + cannot have a side-effect. If a function is pure then it always evaluates to the same value when given the + same arguments. + </p> - <p> - We can write a pure function: - </p> + <p>We can write a pure function:</p> - <InlineEditor> - {`/// A pure function + <InlineEditor> + {`/// A pure function def sum(x: Int32, y: Int32): Int32 = x + y`} - </InlineEditor> + </InlineEditor> - <p> - And we can also write an impure function: - </p> + <p>And we can also write an impure function:</p> - <InlineEditor> - {`/// An impure function + <InlineEditor> + {`/// An impure function def sayHello(): Unit \\ IO = Console.printLine("Hello World")`} - </InlineEditor> + </InlineEditor> - <p> - We can also write a higher-order function that <i>requires</i> a pure function argument: - </p> + <p> + We can also write a higher-order function that <i>requires</i> a pure function argument: + </p> - <InlineEditor> - {`def exists(f: a -> Bool, xs: List[a]): Bool = match xs { + <InlineEditor> + {`def exists(f: a -> Bool, xs: List[a]): Bool = match xs { case Nil => false case x :: rs => if (f(x)) true else exists(f, rs) }`} - </InlineEditor> - - <p> - Here <code>f</code> is a pure function, because every function definition - is <i>implicitly</i> marked as <code>Pure</code> in Flix. - </p> - - <p> - <i>It is a compile-time error to call <code>map</code> with an impure function!</i> - </p> - - <p> - A major challenge for type and effect systems is effect polymorphism. The problem is the - following: for higher-order functions the effect of a function depends on the effects of its - arguments. For example, if map is passed a pure function <code>f</code> then the - expression <code>List.map(f, 1 :: Nil)</code> is pure. On the other hand, if map is passed - an impure function <code>g</code> then the expression <code>List.map(g, 1 :: Nil)</code> is - impure. The effect of map depends on the effect of its first argument: it is effect - polymorphic. - </p> - - <p> - We can express such <i>effect polymorphic</i> function types in Flix. For example: - </p> - - <InlineEditor> - {`def map(f: a -> b \\ ef, xs: List[a]): List[b] \\ ef = match xs { + </InlineEditor> + + <p> + Here <code>f</code> is a pure function, because every function definition is <i>implicitly</i> marked as{' '} + <code>Pure</code> in Flix. + </p> + + <p> + <i> + It is a compile-time error to call <code>map</code> with an impure function! + </i> + </p> + + <p> + A major challenge for type and effect systems is effect polymorphism. The problem is the following: for + higher-order functions the effect of a function depends on the effects of its arguments. For example, if + map is passed a pure function <code>f</code> then the expression <code>List.map(f, 1 :: Nil)</code> is + pure. On the other hand, if map is passed an impure function <code>g</code> then the expression{' '} + <code>List.map(g, 1 :: Nil)</code> is impure. The effect of map depends on the effect of its first + argument: it is effect polymorphic. + </p> + + <p> + We can express such <i>effect polymorphic</i> function types in Flix. For example: + </p> + + <InlineEditor> + {`def map(f: a -> b \\ ef, xs: List[a]): List[b] \\ ef = match xs { case Nil => Nil case x :: rs => f(x) :: map(f, rs) }`} - </InlineEditor> - - <p> - Here the effect <code>map</code> depends on the effect of <code>f</code> (expressed with the - effect parameter <code>ef</code>). - </p> - - <p> - The effect system of Flix is part of what makes the language functional-first: the - programmer can trust that a pure function behaves as a mathematical function. Most other - contemporary programming languages cannot offer such guarantees. - </p> - - <h2>First-class Datalog Constraints</h2> - - <p> - Another unique feature of Flix is its support for logic programming with first-class Datalog - constraints. Datalog is a simple, yet surprisingly powerful, declarative logic programming - language - particularly well-suited for recursive queries on graphs. In Flix, Datalog constraints can - be - embedded <i>inside</i> Flix programs as first-class values that can be stored in local - variables, - passed and returned from functions, and composed with other Datalog program values. In a - way, Flix - is a strongly-typed meta-programming language for Datalog. - </p> - - <InlineEditor> - {`// Declarations of predicate symbols. + </InlineEditor> + + <p> + Here the effect <code>map</code> depends on the effect of <code>f</code> (expressed with the effect + parameter <code>ef</code>). + </p> + + <p> + The effect system of Flix is part of what makes the language functional-first: the programmer can trust + that a pure function behaves as a mathematical function. Most other contemporary programming languages + cannot offer such guarantees. + </p> + + <h2>First-class Datalog Constraints</h2> + + <p> + Another unique feature of Flix is its support for logic programming with first-class Datalog constraints. + Datalog is a simple, yet surprisingly powerful, declarative logic programming language particularly + well-suited for recursive queries on graphs. In Flix, Datalog constraints can be embedded <i>inside</i>{' '} + Flix programs as first-class values that can be stored in local variables, passed and returned from + functions, and composed with other Datalog program values. In a way, Flix is a strongly-typed + meta-programming language for Datalog. + </p> + + <InlineEditor> + {`// Declarations of predicate symbols. rel Road(src: String, speed: Int32, dst: String) rel Connected(src: String, dst: String) @@ -295,22 +275,18 @@ def main(): Unit \\ IO = Road("Hamburg", 130, "Berlin"). }; drivable(g, "Aarhus", "Berlin", 110) |> println`} - </InlineEditor> - - <p> - The solution to a Datalog program, its minimal model, is itself a Datalog program (i.e. a - set of - facts). Consequently, with first-class constraints, it becomes possible to construct - pipelines of - Datalog programs. - </p> - - <p> - First-class Datalog constraints can also be polymorphic, as this example demonstrates: - </p> - - <InlineEditor> - {`def edgesWithNumbers(): #{ LabelledEdge(String, Int32, String) | r } = #{ + </InlineEditor> + + <p> + The solution to a Datalog program, its minimal model, is itself a Datalog program (i.e. a set of facts). + Consequently, with first-class constraints, it becomes possible to construct pipelines of Datalog + programs. + </p> + + <p>First-class Datalog constraints can also be polymorphic, as this example demonstrates:</p> + + <InlineEditor> + {`def edgesWithNumbers(): #{ LabelledEdge(String, Int32, String) | r } = #{ LabelledEdge("a", 1, "b"). LabelledEdge("b", 1, "c"). LabelledEdge("c", 2, "d"). @@ -333,113 +309,103 @@ def main(): Unit \\ IO = select (x, l, z) from LabelledPath(x, l, z) |> println; query edgesWithColor(), closure() select (x, l, z) from LabelledPath(x, l, z) |> println`} - </InlineEditor> - - </Col> - </Row> - - <Row className="mb-3"> - <Col sm={12} md={8}> - - <h1>Innovations</h1> - - <p> - We say that Flix is a next-generation programming language because it pioneers several new - features that are not found in any other contemporary programming language. However, - innovation is not a goal in itself; Flix also builds on decades of research in programming - language theory and relies on well-established theoretical foundations. - </p> - - <h2>Polymorphic Effects</h2> - - <p> - Flix comes with a polymorphic type and effect system. The effect system separates pure - and impure code. If an expression is pure then it always evaluates to the same value and it - cannot have a side-effect. If a function is pure then it always evaluates to the same value - when given the same arguments. - </p> - - <p> - Flix supports <i>effect polymorphism</i> which means that the effect of a higher-order - function can depend on the effect of its function arguments. For example, the effect - of <code>List.map</code> depends on the effect of the function passed to it. That is, - if <code>List.map</code> is given a pure function then computation is pure, whereas if - it is given an impure function then computation is impure. As an another example, - the effect of <code>>></code> (forward function composition) depends on <i>both</i> of - its arguments: composition is only pure if both its function arguments are pure. - </p> - - <p> - The Flix type and effect system is fine-grained and expressive. It is fine-grained because - it precisely captures the purity of every expression and sub-expression. It is expressive - because it allows arbitrary boolean formulas to describe - the effect of an expression. For example, the system can express that a higher-order - function requires <i>at most</i> one impure function. - </p> - - <p> - The Flix type and effect system supports <i>type and effect inference</i>. That is, explicit - type or effect annotations are never required for any program fragment. (However, as a - design choice, type and effect annotations are required for every top-level definition.) The - inference is <i>complete</i> which means that it never infers the wrong type or effect, i.e. - annotations are never required to guide the type checker. - </p> - - <p> - The theoretical foundation of the Flix type and effect system is based on the Hindley-Milner - type system extended with boolean constraints. Type inference is supported by - an extension of Algorithm W with boolean unification. For more details, we refer to our - research papers. - </p> - - <h2>First-class Datalog Constraints</h2> - - <p> - Datalog is a simple, yet surprisingly powerful, declarative logic programming language. A - Datalog program is a collection of constraints. Each constraint is either a fact or a rule. - A Datalog rule is logic formula that allows us to derive new facts from existing facts. - </p> - - <p> - Every Datalog program has a unique solution; its so-called <i>minimal model</i>. - The minimal model always exists and is always computable, i.e. evaluation of a Datalog - program always terminates with the same solution. In Datalog, unlike in Prolog, the order - of constraints and of clauses within a rule is immaterial. That is, a Datalog program - can be freely reordered without changing its meaning. - </p> - - <p> - Datalog, unlike Prolog, is <i>not</i> Turing-complete: there are a programs that cannot be - expressed in Datalog. This is necessarily so, otherwise Datalog could not guarantee - termination. - </p> - - <p> - Flix supports Datalog constraints as <i>first-class values</i> that can be passed around, - composed with other constraints, and solved. The solution (i.e. minimal model) of a - constraint set is another constraint set, hence it is possible to construct pipelines of - Datalog computations within a Flix program. - </p> - - <p> - Flix can be thought of as a meta-programming language for Datalog. The Flix type system - and stratification algorithm guarantees the well-formedness of Datalog programs constructed - at run-time. Moreover, Flix significantly increases the expressive power of Datalog by - allowing guard expressions and expressions as head terms in Datalog rules. - </p> - - <p> - Alternatively, Flix can be thought of as a functional programming language with a very - powerful embedded query language. A Flix programmer can use first-class Datalog constraints - to simply, elegantly, and efficiently solve fixpoint computations inside functional code. - It should be noted that Datalog is strictly more expressive than relational algebra (~= - simple SQL). - </p> - - </Col> - </Row> - </Container>); - } + </InlineEditor> + </Col> + </Row> + + <Row className="mb-3"> + <Col sm={12} md={8}> + <h1>Innovations</h1> + + <p> + We say that Flix is a next-generation programming language because it pioneers several new features that + are not found in any other contemporary programming language. However, innovation is not a goal in itself; + Flix also builds on decades of research in programming language theory and relies on well-established + theoretical foundations. + </p> + + <h2>Polymorphic Effects</h2> + + <p> + Flix comes with a polymorphic type and effect system. The effect system separates pure and impure code. If + an expression is pure then it always evaluates to the same value and it cannot have a side-effect. If a + function is pure then it always evaluates to the same value when given the same arguments. + </p> + + <p> + Flix supports <i>effect polymorphism</i> which means that the effect of a higher-order function can depend + on the effect of its function arguments. For example, the effect of <code>List.map</code> depends on the + effect of the function passed to it. That is, if <code>List.map</code> is given a pure function then + computation is pure, whereas if it is given an impure function then computation is impure. As an another + example, the effect of <code>>></code> (forward function composition) depends on <i>both</i> of its + arguments: composition is only pure if both its function arguments are pure. + </p> + + <p> + The Flix type and effect system is fine-grained and expressive. It is fine-grained because it precisely + captures the purity of every expression and sub-expression. It is expressive because it allows arbitrary + boolean formulas to describe the effect of an expression. For example, the system can express that a + higher-order function requires <i>at most</i> one impure function. + </p> + + <p> + The Flix type and effect system supports <i>type and effect inference</i>. That is, explicit type or + effect annotations are never required for any program fragment. (However, as a design choice, type and + effect annotations are required for every top-level definition.) The inference is <i>complete</i> which + means that it never infers the wrong type or effect, i.e. annotations are never required to guide the type + checker. + </p> + + <p> + The theoretical foundation of the Flix type and effect system is based on the Hindley-Milner type system + extended with boolean constraints. Type inference is supported by an extension of Algorithm W with boolean + unification. For more details, we refer to our research papers. + </p> + + <h2>First-class Datalog Constraints</h2> + + <p> + Datalog is a simple, yet surprisingly powerful, declarative logic programming language. A Datalog program + is a collection of constraints. Each constraint is either a fact or a rule. A Datalog rule is logic + formula that allows us to derive new facts from existing facts. + </p> + + <p> + Every Datalog program has a unique solution; its so-called <i>minimal model</i>. The minimal model always + exists and is always computable, i.e. evaluation of a Datalog program always terminates with the same + solution. In Datalog, unlike in Prolog, the order of constraints and of clauses within a rule is + immaterial. That is, a Datalog program can be freely reordered without changing its meaning. + </p> + + <p> + Datalog, unlike Prolog, is <i>not</i> Turing-complete: there are a programs that cannot be expressed in + Datalog. This is necessarily so, otherwise Datalog could not guarantee termination. + </p> + + <p> + Flix supports Datalog constraints as <i>first-class values</i> that can be passed around, composed with + other constraints, and solved. The solution (i.e. minimal model) of a constraint set is another constraint + set, hence it is possible to construct pipelines of Datalog computations within a Flix program. + </p> + + <p> + Flix can be thought of as a meta-programming language for Datalog. The Flix type system and stratification + algorithm guarantees the well-formedness of Datalog programs constructed at run-time. Moreover, Flix + significantly increases the expressive power of Datalog by allowing guard expressions and expressions as + head terms in Datalog rules. + </p> + + <p> + Alternatively, Flix can be thought of as a functional programming language with a very powerful embedded + query language. A Flix programmer can use first-class Datalog constraints to simply, elegantly, and + efficiently solve fixpoint computations inside functional code. It should be noted that Datalog is + strictly more expressive than relational algebra (~= simple SQL). + </p> + </Col> + </Row> + </Container> + ) + } } -export default About; +export default About diff --git a/src/page/Blog.js b/src/page/Blog.js index a3a9b9b..9159dcd 100644 --- a/src/page/Blog.js +++ b/src/page/Blog.js @@ -1,102 +1,91 @@ -import React, {Component} from 'react'; -import {Col, Container, Row} from "reactstrap"; -import {Link} from "react-router-dom"; -import {Route, Switch} from "react-router"; -import ProgrammingLanguageDefense from "./blog/ProgrammingLanguageDefense"; -import DesignFlaws from "./blog/DesignFlaws"; -import Naming from "./blog/Naming"; -import Redundancies from "./blog/Redundancies"; -import PolymorphicEffects from "./blog/PolymorphicEffects"; +import React, { Component } from 'react' +import { Col, Container, Row } from 'reactstrap' +import { Link } from 'react-router-dom' +import { Route, Switch } from 'react-router' +import ProgrammingLanguageDefense from './blog/ProgrammingLanguageDefense' +import DesignFlaws from './blog/DesignFlaws' +import Naming from './blog/Naming' +import Redundancies from './blog/Redundancies' +import PolymorphicEffects from './blog/PolymorphicEffects' class Blog extends Component { - - componentDidMount() { - if (!document.title) { - document.title = "Flix | Blog"; - } + componentDidMount() { + if (!document.title) { + document.title = 'Flix | Blog' } + } - render() { - return ( - <Container> - <Switch> - <Route exact path="/blog/"> - <Row className="mb-3"> - <Col> - <h1>Blog</h1> - - <p> - We maintain a blog about the development of the Flix programming language. - The blog is slow-moving since most of our writing bandwidth is directed towards - writing documentation and research papers. - </p> - - <p> - The blog has a more personal style and its intended audience is primarily - programming language enthusiasts. - </p> + render() { + return ( + <Container> + <Switch> + <Route exact path="/blog/"> + <Row className="mb-3"> + <Col> + <h1>Blog</h1> - </Col> - </Row> + <p> + We maintain a blog about the development of the Flix programming language. The blog is slow-moving + since most of our writing bandwidth is directed towards writing documentation and research papers. + </p> - <Row className="mb-3"> - <Col> - <ul> - <li> - <Link to="/blog/in-defense-of-programming-languages/"> - In Defense of Programming Languages - </Link> - </li> - <li> - <Link to="/blog/taming-impurity-with-polymorphic-effects/"> - Taming Impurity with Polymorphic Effects - </Link> - </li> - <li> - <Link to="/blog/naming-functional-and-destructive-operations/"> - Naming Functional and Destructive Operations - </Link> - </li> - <li> - <Link to="/blog/redundancies-as-compile-time-errors/"> - Redundancies as Compile-Time Errors - </Link> - </li> - <li> - <Link to="/blog/design-flaws-in-flix/"> - Design Flaws in the Flix Programming Language - </Link> - </li> - </ul> - </Col> - </Row> - </Route> + <p> + The blog has a more personal style and its intended audience is primarily programming language + enthusiasts. + </p> + </Col> + </Row> + <Row className="mb-3"> + <Col> + <ul> + <li> + <Link to="/blog/in-defense-of-programming-languages/">In Defense of Programming Languages</Link> + </li> + <li> + <Link to="/blog/taming-impurity-with-polymorphic-effects/"> + Taming Impurity with Polymorphic Effects + </Link> + </li> + <li> + <Link to="/blog/naming-functional-and-destructive-operations/"> + Naming Functional and Destructive Operations + </Link> + </li> + <li> + <Link to="/blog/redundancies-as-compile-time-errors/">Redundancies as Compile-Time Errors</Link> + </li> + <li> + <Link to="/blog/design-flaws-in-flix/">Design Flaws in the Flix Programming Language</Link> + </li> + </ul> + </Col> + </Row> + </Route> - <Route path="/blog/in-defense-of-programming-languages/"> - <ProgrammingLanguageDefense/> - </Route> + <Route path="/blog/in-defense-of-programming-languages/"> + <ProgrammingLanguageDefense /> + </Route> - <Route path="/blog/taming-impurity-with-polymorphic-effects/"> - <PolymorphicEffects/> - </Route> + <Route path="/blog/taming-impurity-with-polymorphic-effects/"> + <PolymorphicEffects /> + </Route> - <Route path="/blog/naming-functional-and-destructive-operations/"> - <Naming/> - </Route> + <Route path="/blog/naming-functional-and-destructive-operations/"> + <Naming /> + </Route> - <Route path="/blog/redundancies-as-compile-time-errors/"> - <Redundancies/> - </Route> + <Route path="/blog/redundancies-as-compile-time-errors/"> + <Redundancies /> + </Route> - <Route path="/blog/design-flaws-in-flix/"> - <DesignFlaws/> - </Route> - - </Switch> - </Container> - ); - } + <Route path="/blog/design-flaws-in-flix/"> + <DesignFlaws /> + </Route> + </Switch> + </Container> + ) + } } -export default Blog; +export default Blog diff --git a/src/page/Contribute.js b/src/page/Contribute.js index 7a46032..fc9d4a0 100644 --- a/src/page/Contribute.js +++ b/src/page/Contribute.js @@ -1,100 +1,91 @@ -import React, {Component} from 'react'; -import {Card, CardBody, CardTitle, Col, Container, Row} from "reactstrap"; +import React, { Component } from 'react' +import { Card, CardBody, CardTitle, Col, Container, Row } from 'reactstrap' class Contribute extends Component { + componentDidMount() { + document.title = 'Flix | Contribute' + } - componentDidMount() { - document.title = "Flix | Contribute"; - } + render() { + return ( + <Container> + <Row className="mb-3"> + <Col> + <h1>Contribute</h1> - render() { - return ( - <Container> - <Row className="mb-3"> - <Col> + <p> + Flix is developed at <a href="http://cs.au.dk/research/programming-languages/">Aarhus University</a>, at + the <a href="http://plg.uwaterloo.ca"> University of Waterloo</a>, and by a community of{' '} + <a href="https://github.com/flix/flix/graphs/contributors">open source contributors</a>. + </p> - <h1>Contribute</h1> + <p> + Flix is open-source and freely available under the{' '} + <a href="https://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a> license. + </p> - <p> - Flix is developed at <a - href="http://cs.au.dk/research/programming-languages/">Aarhus - University</a>, at the <a href="http://plg.uwaterloo.ca"> University of Waterloo</a>, and by - a community of <a href="https://github.com/flix/flix/graphs/contributors">open source - contributors</a>. - </p> + <p> + All source code is available on <a href="https://github.com/flix/flix">GitHub</a>. We organize development + using <a href="https://github.com/flix/flix/issues">GitHub issues</a> and{' '} + <a href="https://gitter.im/flix/Lobby">Gitter</a>. + </p> - <p> - Flix is open-source and freely available under the <a - href="https://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a> license. - </p> + <p> + If you are interested working on Flix, please feel free to reach out to us. We have already had several + positive experiences with mentorship and open source contributors. + </p> + </Col> + </Row> - <p> - All source code is available on <a - href="https://github.com/flix/flix">GitHub</a>. + <h2>Projects</h2> - We organize development using <a - href="https://github.com/flix/flix/issues">GitHub issues</a> and <a - href="https://gitter.im/flix/Lobby">Gitter</a>. - </p> - - <p> - If you are interested working on Flix, please feel free to reach out to us. We have already - had several positive experiences with mentorship and open source contributors. - </p> - </Col> - </Row> - - <h2>Projects</h2> - - <Row className="mb-3"> - <Col md="4"> - <Card className="h-100"> - <CardBody> - <CardTitle>Open Source Mentoring</CardTitle> - <p> - We are more than happy to mentor someone who is interested in working on compilers - and/or programming language design and wants to contribute to Flix. We have already - had several positive experiences working with open source - contributors. - </p> - </CardBody> - </Card> - </Col> - - <Col md="4"> - <Card className="h-100"> - <CardBody> - <CardTitle>Talent Track Projects</CardTitle> - <p> - Aarhus University offers a talent track program for capable students that are in - their second or third year of studies and are interested in working on a research - project for up to one year as an extracurricular activity. - </p> - </CardBody> - </Card> - </Col> + <Row className="mb-3"> + <Col md="4"> + <Card className="h-100"> + <CardBody> + <CardTitle>Open Source Mentoring</CardTitle> + <p> + We are more than happy to mentor someone who is interested in working on compilers and/or programming + language design and wants to contribute to Flix. We have already had several positive experiences + working with open source contributors. + </p> + </CardBody> + </Card> + </Col> - <Col md="4"> - <Card className="h-100"> - <CardBody> - <CardTitle>Bachelor and Master Projects</CardTitle> - <p> - If you are a bachelor or master student at Aarhus University you can - write your thesis on a topic related to Flix. - </p> - </CardBody> - </Card> - </Col> - </Row> + <Col md="4"> + <Card className="h-100"> + <CardBody> + <CardTitle>Talent Track Projects</CardTitle> + <p> + Aarhus University offers a talent track program for capable students that are in their second or third + year of studies and are interested in working on a research project for up to one year as an + extracurricular activity. + </p> + </CardBody> + </Card> + </Col> + <Col md="4"> + <Card className="h-100"> + <CardBody> + <CardTitle>Bachelor and Master Projects</CardTitle> <p> - If you want to become involved, send us a ping on <a - href="https://gitter.im/flix/Lobby">Gitter</a>, and we can have a chat about your - interests. + If you are a bachelor or master student at Aarhus University you can write your thesis on a topic + related to Flix. </p> - </Container> - ); - } + </CardBody> + </Card> + </Col> + </Row> + + <p> + If you want to become involved, send us a ping on <a href="https://gitter.im/flix/Lobby">Gitter</a>, and we + can have a chat about your interests. + </p> + </Container> + ) + } } -export default Contribute; +export default Contribute diff --git a/src/page/Documentation.js b/src/page/Documentation.js index 5455589..f953e00 100644 --- a/src/page/Documentation.js +++ b/src/page/Documentation.js @@ -1,155 +1,136 @@ -import React, { Component } from 'react'; -import { Card, CardSubtitle, CardText, CardTitle, Col, Container, Row } from "reactstrap"; -import { Link } from "react-router-dom"; +import React, { Component } from 'react' +import { Card, CardSubtitle, CardText, CardTitle, Col, Container, Row } from 'reactstrap' +import { Link } from 'react-router-dom' -import { FaBookReader } from 'react-icons/fa'; -import { FaStream } from 'react-icons/fa'; -import { FaMicroblog } from 'react-icons/fa'; -import { FaGitter } from 'react-icons/fa'; -import { FaGithub } from 'react-icons/fa'; -import { FaRegLaughSquint } from 'react-icons/fa'; -import { MdSchool } from 'react-icons/md'; -import { GoGraph } from 'react-icons/go'; +import { FaBookReader } from 'react-icons/fa' +import { FaStream } from 'react-icons/fa' +import { FaMicroblog } from 'react-icons/fa' +import { FaGitter } from 'react-icons/fa' +import { FaGithub } from 'react-icons/fa' +import { FaRegLaughSquint } from 'react-icons/fa' +import { MdSchool } from 'react-icons/md' +import { GoGraph } from 'react-icons/go' class Documentation extends Component { + componentDidMount() { + document.title = 'Flix | Documentation' + } - componentDidMount() { - document.title = "Flix | Documentation"; - } + render() { + return ( + <Container> + <Row className="mb-3"> + <Col> + <h1>Documentation</h1> + </Col> + </Row> - render() { - return ( - <Container> - <Row className="mb-3"> - <Col> - <h1>Documentation</h1> - </Col> - </Row> + <Row className="mb-4"> + <Col md="6"> + <a href="https://doc.flix.dev/" className="text-primary"> + <Card body className="h-100"> + <CardSubtitle className="text-center m-4"> + <FaBookReader style={{ fontSize: '6em' }} /> + </CardSubtitle> + <CardTitle className="text-center">Programming Flix</CardTitle> + <CardText className="text-dark"> + The book provides an introduction to Flix for functional programmers. The book demonstrates the core + concepts of Flix through several examples. + </CardText> + </Card> + </a> + </Col> + <Col md="6"> + <a href="https://api.flix.dev/" className="text-success"> + <Card body className="h-100"> + <CardSubtitle className="text-center m-4"> + <FaStream style={{ fontSize: '6em' }} /> + </CardSubtitle> + <CardTitle className="text-center">Standard Library</CardTitle> + <CardText className="text-dark"> + The documentation provides a Javadoc-style description of the Flix library. + </CardText> + </Card> + </a> + </Col> + </Row> - <Row className="mb-4"> - <Col md="6"> - <a href="https://doc.flix.dev/" className="text-primary"> - <Card body className="h-100"> - <CardSubtitle className="text-center m-4"> - <FaBookReader style={{ fontSize: '6em' }} /> - </CardSubtitle> - <CardTitle className="text-center"> - Programming Flix - </CardTitle> - <CardText className="text-dark"> - The book provides an introduction to Flix for functional programmers. The book - demonstrates the core concepts of Flix through several examples. - </CardText> - </Card> - </a> - </Col> - <Col md="6"> - <a href="https://api.flix.dev/" className="text-success"> - <Card body className="h-100"> - <CardSubtitle className="text-center m-4"> - <FaStream style={{ fontSize: '6em' }} /> - </CardSubtitle> - <CardTitle className="text-center"> - Standard Library - </CardTitle> - <CardText className="text-dark"> - The documentation provides a Javadoc-style description of the Flix library. - </CardText> - </Card> - </a> - </Col> - </Row> + <Row className="mb-3"> + <Col> + <p>You may also be interested in these additional resources:</p> + </Col> + </Row> - <Row className="mb-3"> - <Col> - <p> - You may also be interested in these additional resources: - </p> - </Col> - </Row> + <Row className="mb-3"> + <Col lg="2"> + <Link to="/research"> + <Card body className="h-100"> + <CardSubtitle className="text-center m-4 text-black-50"> + <MdSchool style={{ fontSize: '3em' }} /> + </CardSubtitle> + <CardTitle className="text-center link-primary">Research Papers</CardTitle> + </Card> + </Link> + </Col> - <Row className="mb-3"> - <Col lg="2"> - <Link to="/research"> - <Card body className="h-100"> - <CardSubtitle className="text-center m-4 text-black-50"> - <MdSchool style={{ fontSize: '3em' }} /> - </CardSubtitle> - <CardTitle className="text-center link-primary"> - Research Papers - </CardTitle> - </Card> - </Link> - </Col> + <Col lg="2"> + <Link to="/blog/"> + <Card body className="h-100"> + <CardSubtitle className="text-center m-4 text-black-50"> + <FaMicroblog style={{ fontSize: '3em' }} /> + </CardSubtitle> + <CardTitle className="text-center link-primary">Blog</CardTitle> + </Card> + </Link> + </Col> - <Col lg="2"> - <Link to="/blog/"> - <Card body className="h-100"> - <CardSubtitle className="text-center m-4 text-black-50"> - <FaMicroblog style={{ fontSize: '3em' }} /> - </CardSubtitle> - <CardTitle className="text-center link-primary"> - Blog - </CardTitle> - </Card> - </Link> - </Col> + <Col lg="2"> + <a href="https://gitter.im/flix/Lobby"> + <Card body className="h-100"> + <CardSubtitle className="text-center m-4 text-black-50"> + <FaGitter style={{ fontSize: '3em' }} /> + </CardSubtitle> + <CardTitle className="text-center link-primary">Gitter</CardTitle> + </Card> + </a> + </Col> - <Col lg="2"> - <a href="https://gitter.im/flix/Lobby"> - <Card body className="h-100"> - <CardSubtitle className="text-center m-4 text-black-50"> - <FaGitter style={{ fontSize: '3em' }} /> - </CardSubtitle> - <CardTitle className="text-center link-primary"> - Gitter - </CardTitle> - </Card> - </a> - </Col> + <Col lg="2"> + <a href="https://github.com/flix/flix"> + <Card body className="h-100"> + <CardSubtitle className="text-center m-4 text-black-50"> + <FaGithub style={{ fontSize: '3em' }} /> + </CardSubtitle> + <CardTitle className="text-center link-primary">GitHub</CardTitle> + </Card> + </a> + </Col> - <Col lg="2"> - <a href="https://github.com/flix/flix"> - <Card body className="h-100"> - <CardSubtitle className="text-center m-4 text-black-50"> - <FaGithub style={{ fontSize: '3em' }} /> - </CardSubtitle> - <CardTitle className="text-center link-primary"> - GitHub - </CardTitle> - </Card> - </a> - </Col> + <Col lg="2"> + <a href="https://arewefast.flix.dev/"> + <Card body className="h-100"> + <CardSubtitle className="text-center m-4 text-black-50"> + <GoGraph style={{ fontSize: '3em' }} /> + </CardSubtitle> + <CardTitle className="text-center link-primary">Compiler Perf</CardTitle> + </Card> + </a> + </Col> - <Col lg="2"> - <a href="https://arewefast.flix.dev/"> - <Card body className="h-100"> - <CardSubtitle className="text-center m-4 text-black-50"> - <GoGraph style={{ fontSize: '3em' }} /> - </CardSubtitle> - <CardTitle className="text-center link-primary"> - Compiler Perf - </CardTitle> - </Card> - </a> - </Col> - - <Col lg="2"> - <Link to="/misc/checklist"> - <Card body className="h-100"> - <CardSubtitle className="text-center m-4 text-black-50"> - <FaRegLaughSquint style={{ fontSize: '3em' }} /> - </CardSubtitle> - <CardTitle className="text-center link-primary"> - Language Checklist - </CardTitle> - </Card> - </Link> - </Col> - </Row> - </Container> - ); - } + <Col lg="2"> + <Link to="/misc/checklist"> + <Card body className="h-100"> + <CardSubtitle className="text-center m-4 text-black-50"> + <FaRegLaughSquint style={{ fontSize: '3em' }} /> + </CardSubtitle> + <CardTitle className="text-center link-primary">Language Checklist</CardTitle> + </Card> + </Link> + </Col> + </Row> + </Container> + ) + } } -export default Documentation; +export default Documentation diff --git a/src/page/Faq.js b/src/page/Faq.js index 9718c1e..4df212d 100644 --- a/src/page/Faq.js +++ b/src/page/Faq.js @@ -1,674 +1,567 @@ -import React, {Component} from 'react'; -import {Card, CardBody, CardTitle, Table} from 'reactstrap'; -import {Container} from 'reactstrap'; -import {Link} from "react-router-dom"; +import React, { Component } from 'react' +import { Card, CardBody, CardTitle, Table } from 'reactstrap' +import { Container } from 'reactstrap' +import { Link } from 'react-router-dom' class Faq extends Component { - - componentDidMount() { - document.title = "Flix | FAQ"; - } - - render() { - return ( - <Container> - <h1>Frequently Asked Questions</h1> - - <p className="mb-3"> - A collection of information that did not seem to fit in anywhere else. - </p> - - <QA> - <Question> - Are you looking for help with the compiler or language design? - </Question> - <Answer> - Yes! We welcome any contributions and we are happy to mentor someone who wants to work - on the compiler. We are also open to general feedback and discussion about the language - design. Head on over to <a href="https://github.com/flix/flix">GitHub</a> or <a - href="https://gitter.im/flix/Lobby">Gitter</a> and reach out to us! - </Answer> - </QA> - - <QA> - <Question> - Does Flix support integration with Java, Kotlin, Scala etc? - </Question> - <Answer> - <p> - Yes, with the <code>import</code> mechanism. - </p> - </Answer> - </QA> - - <QA> - <Question> - Flix looks quite similar to Scala. How are the two languages related? - </Question> - <Answer> - <p> - Flix borrows a lot of syntax from Scala, hence the two languages have a similar feel. - We think Scala made many good design choices with respect to syntax, including: - (a) the use of short keywords, - (b) the <code>x : T</code> syntax for type annotations, - (c) the <code>List[Int32]</code> syntax for type parameters, and - (d) <code>if</code>, <code>match</code>, etc. as expressions. - </p> - - <p> - Other than syntax, the two languages are very different: Scala is object-oriented, Flix is - not. - Scala has sub-typing, Flix does not. The Scala type system is unsound and has imperfect - type inference, whereas the Flix type system is both sound and supports type inference. - </p> - </Answer> - </QA> - - <QA> - <Question> - Does Flix have a read-eval-print-loop (REPL)? - </Question> - - <Answer> - No, but the compiler does have an interactive mode that can be started by passing - the <code>--interactive</code> argument. - </Answer> - </QA> - - <QA> - <Question> - Does Flix have IDE support? Language Server Protocol (LSP) support? - </Question> - <Answer> - Yes. There is a <a href="https://marketplace.visualstudio.com/items?itemName=flix.flix">Visual - Studio Code plugin available for Flix</a>. - </Answer> - </QA> - - <QA> - <Question> - Does Flix compile to LLVM? - </Question> - <Answer> - No and we don't have any plans to target LLVM. - </Answer> - </QA> - - <QA> - <Question> - Does Flix compile to WebAssembly (WASM)? - </Question> - <Answer> - No, not at the moment. It is something we are open to, but we are waiting for WebAssembly to - gain a garbage collector and tail calls. - </Answer> - </QA> - - <QA> - <Question> - Why does Flix target the Java Virtual Machine (JVM)? - </Question> - <Answer> - The Java Virtual Machine is a state-of-the-art virtual machine that runs on virtually every - platform, comes with a huge ecosystem of libraries, and supports garbage collection. While not - the ideal target for functional programming languages, due to its absence of tail call - instructions, it is still a strong choice. Moreover, if <a - href="https://openjdk.java.net/projects/loom/">Project Loom</a> (or similar efforts) turn out - successful then the JVM will offer an unbeatable feature set. - </Answer> - </QA> - - <QA> - <Question> - Is the Flix type system sound? - </Question> - <Answer> - Yes. It is based on Hindley-Milner. - </Answer> - </QA> - - <QA> - <Question> - I want to learn Flix! What should I know about before hand? - </Question> - <Answer> - <p> - At the moment, Flix has not yet reached version 1.0. That means you will be an early - adopter, so you should expect for the language to evolve and be prepared for the rare - compiler bug. (The Flix compiler has 9,500 manually written tests and we - take correctness seriously.) - </p> - - <p> - To write Flix programs, a solid background in functional programming is useful. That means - prior experience with OCaml, Haskell, Scala, or similar programming languages. - </p> - </Answer> - </QA> - - <QA> - <Question> - What is the best way to start learning Flix? - </Question> - <Answer> - <p> - We recommend that you start with a small offering to the Great Dreamer, the Sleeper of - R'lyeh, Cthulhu. And coffee. Lots of coffee. All kidding aside, the best place to start is - to look at the examples and to read the <a href="https://doc.flix.dev/">Programming - Flix</a> book. - </p> - - <p> - If you get stuck or need help feel free to reach out to us on Gitter. - </p> - </Answer> - </QA> - - <QA> - <Question> - Is Flix a domain specific language (DSL)? - </Question> - <Answer> - <p> - No, Flix is a full-blown functional programming language. - </p> - - <p> - That said, Flix could be considered a meta-programming language for Datalog. - </p> - </Answer> - </QA> - - <QA> - <Question> - What is the runtime performance of Flix programs? - </Question> - <Answer> - <p> - Flix runs on the Java Virtual Machine (JVM) hence the performance of Flix is limited by the - performance of the JVM. Luckily, the JVM is a mature and performant virtual machine. Flix - uses monomorphization which eliminates boxing and in theory can make code execute faster - than ordinary Java / Kotlin / Scala code. However, Flix also features full tail call - elimination - which has some run-time performance cost. - </p> - - <p> - Our goal to be faster than any interpreted language and within a few factors of - equivalent functional Scala code. - </p> - </Answer> - </QA> - - <QA> - <Question> - Haskell and OCaml compile to native code thus – by definition – they must be faster than Flix. - </Question> - <Answer> - This is not necessarily true. For example, Java sometimes beats both <a - href="https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/ocaml-java.html">OCaml</a> and <a - href="https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/haskell.html">Haskell</a> in <a - href="https://benchmarksgame-team.pages.debian.net/benchmarksgame/index.html">The Computer - Language Benchmarks Game</a>. - </Answer> - </QA> - - <QA> - <Question> - What is the performance of the Flix compiler? - </Question> - <Answer> - <p> - To answer this question, it is important to distinguish between <a - href="https://en.wikipedia.org/wiki/Latency_(engineering)">latency</a> and <a - href="https://en.wikipedia.org/wiki/Throughput">throughput</a>. - </p> - - <p> - The Flix compiler runs on the JVM hence startup times can be expensive, i.e. the compiler - has high latency. However, once the JVM has warmed up the compiler is quite fast, i.e. has - high throughput. - </p> - - <p> - A simple experiment shows that the compiler runs about <code>20.0x</code> times faster - when warmed up compared to when cold. We estimate that Flix, when warmed up, compiles - around <code>20,000</code> lines of code per second, which we believe to be faster than the - Scala compiler, but slower than the Java compiler. We take compiler performance - seriously and continuously track the <a href="https://arewefast.flix.dev/">performance of - the compiler</a>. - </p> - </Answer> - </QA> - - <QA> - <Question> - Ok, but really, what is the performance of the Flix compiler? - </Question> - <Answer> - <p> - Compiler throughput on an Intel i5-K8600k with 16GB of RAM. - </p> - - <p> - Experimental results from the 30th of May 2020. - </p> - - <Table striped> - <thead> - <tr> - <th className="text-center" style={{"width": "20%"}}>Threads</th> - <th className="text-right">Throughput (lines/sec)</th> - <th className="text-right">Ratio</th> - </tr> - </thead> - <tbody> - <tr> - <td className="text-center">1</td> - <td className="text-right">9,673</td> - <td className="text-right">1.0x</td> - </tr> - <tr> - <td className="text-center">2</td> - <td className="text-right">14,482</td> - <td className="text-right">1.5x</td> - </tr> - <tr> - <td className="text-center">3</td> - <td className="text-right">17,100</td> - <td className="text-right">1.8x</td> - </tr> - <tr> - <td className="text-center">4</td> - <td className="text-right">18,722</td> - <td className="text-right">1.9x</td> - </tr> - <tr> - <td className="text-center">5</td> - <td className="text-right">20,118</td> - <td className="text-right">2.1x</td> - </tr> - <tr> - <td className="text-center">6</td> - <td className="text-right">21,052</td> - <td className="text-right">2.2x</td> - </tr> - </tbody> - </Table> - </Answer> - </QA> - - <QA> - <Question> - What features are <i>not</i> supported by Flix? - </Question> - - <Answer> - <p> - Flix will, <i>by design</i>, not support any of the following features: - </p> - - <Table striped> - <thead> - <tr> - <th style={{"width": "20%"}}>Feature</th> - <th>Reason</th> - </tr> - </thead> - <tbody> - <tr> - <td>Exceptions</td> - <td>Exceptions have been used to deal with two types of errors that may arise during - execution of a program: predictable errors (e.g. a file does not exist) and program - bugs (e.g. stack overflow). Flix has no exceptions. Instead, all predictable errors - should be encoded as partial functions (e.g. using <code>Option</code>) or as - potentially error returning functions (e.g. using <code>Result</code>). We are still - in the process of deciding how to handle program bugs. - </td> - </tr> - <tr> - <td>Null Values</td> - <td> - Null, famously called <a href="https://en.wikipedia.org/wiki/Tony_Hoare">Tony - Hoare's billion dollar mistake</a>, is simply a bad solution to the problem of how - to represent the (potential) absence of a value. Instead, in Flix, you should use - the <code>Option</code> data type. - </td> - </tr> - <tr> - <td>Non-Total Functions</td> - <td> - The Flix standard library has been deliberately designed to avoid common - programming mistakes. We want functions that are safe and have accurate type - signatures. For example, unlike Scala or Haskell, - the <code>List.head</code> function returns an <code>Option</code> since we cannot - in general guarantee that a list is non-empty. - </td> - </tr> - <tr> - <td>Silent Coercions</td> - <td> - Implicit coercions between data types (e.g. between booleans and other values or - between enums and integers) is a rich source of programming mistakes. In Flix, - no type is ever converted to another type without explicit instruction from the - programmer. - </td> - </tr> - <tr> - <td>No Code Before Main</td> - <td> - In Flix, no code is ever executed before main. Flix has no static initializers (or - similar constructs) which are difficult to reason about, error-prone, and often lead - to buggy code. - </td> - </tr> - <tr> - <td>Equality and Assignment Confusion</td> - <td> - In Flix, the equality test operator (<code>==</code>) is different from the - assignment operator (<code>:=</code>) which is different from the equality sign - (<code>=</code>) used in definitions and let-bindings. Flix has been designed such - that programs that mistake one for the other is unlikely to compile. - </td> - </tr> - <tr> - <td>Undefined Behavior</td> - <td>Undefined behavior is frequently the cause of program bugs and - vulnerabilities. We want every Flix program to have a well-defined semantics. - </td> - </tr> - </tbody> - </Table> - - <p> - This list was partially inspired by the blog post <a - href="https://graydon2.dreamwidth.org/218040.html">things rust shipped without</a>. - </p> - </Answer> - </QA> - - <QA> - <Question> - What controversial design choices are made in Flix? - </Question> - - <Answer> - - <p> - The following design choices may be considered controversial by some: - </p> - - <ul> - <li> - Unused variables are compile-time errors. - </li> - <li> - Shadowed variables are compile-time errors. - </li> - <li> - Unused definitions, type declarations, etc. are compile-time errors. - </li> - <li> - No variadic or labelled function arguments. - </li> - <li> - No warnings, only compile-time errors. - </li> - <li> - <a href="https://www.hillelwayne.com/post/divide-by-zero/">Dividing by zero yields - zero</a>. - </li> - </ul> - - </Answer> - </QA> - - <QA> - <Question> - Who works on Flix? Is Flix a hobby project? - </Question> - <Answer> - <p> - Flix is a research project carried out by faculty and students at <a - href="http://cs.au.dk/">Aarhus University</a> and the <a href="http://uwaterloo.ca/">University - of Waterloo</a>. - </p> - - <p> - Flix is partially supported by a grant of 2,500,000 DKK from the <a href="http://dff.dk/">Independent - Research Fund of Denmark.</a> - </p> - </Answer> - </QA> - - <QA> - <Question> - Where does the "Flix" name come from? - </Question> - <Answer> - We do not entirely remember, but we believe it came from <span className="text-monospace">FIXpoint Language</span>. - </Answer> - </QA> - - <QA> - <Question> - Does Flix have a network library with streaming support? - </Question> - <Answer> - Not yet, but maybe we could call it net-flix? - </Answer> - </QA> - - <QA> - <Question> - You do not seem to understand parsing / type theory / code generation / computers! - </Question> - <Answer> - We are happy to learn and to revisit design decisions if we come to a greater understanding - of the problem at hand. If you think we have overlooked something, we would be happy to talk - about it if you post a ticket on GitHub or write to us on Gitter. - </Answer> - </QA> - - <QA> - <Question> - Why does the website require JavaScript? - </Question> - <Answer> - We built the website using the popular React framework. We use JavaScript for the online code - editor. Using React was easy. Ultimately, we want to spend our time writing compilers, not - writing websites. - </Answer> - </QA> - - <QA> - <Question> - The page does not load without JavaScript enabled. If I cannot even view the website without - that bloat, I wonder what the language is like? - </Question> - <Answer> - Indeed, if your computer is too old to run a modern browser that supports JavaScript then - probably your computer is too old to run a modern JVM that supports Flix. Sorry. - </Answer> - </QA> - - <QA> - <Question> - It appears that an example on the website does not work? - </Question> - <Answer> - <p> - The latest compiler version and the website is not always in sync, hence occasionally some - examples may stop to work. Feel free to open a bug report if this happens. - </p> - - <p> - Occasionally a mischievous visitor will crash the online editor (or rather the virtual - machine on which the compiler runs). We usually discover and fix this within a few days. - </p> - </Answer> - </QA> - - <QA> - <Question> - The language is probably great from a technical point of view, but unless Apple, Google, - Mozilla, or Microsoft is on-board it is pointless. - </Question> - <Answer> - <p> - Yes, no programming language developed outside of those four corporations have ever been - successful. See also C, C++, Java, Python, PHP, MatLab, Perl, R, Ruby, Scala, ... - </p> - - <p> - That said, if you work for a company and would like to help sponsor Flix, please feel free - to reach out to us :) - </p> - </Answer> - </QA> - - <QA> - <Question> - Wow! Amazing! A language where you can iterate through lists and call functions recursively. - </Question> - <Answer> - Magical, isn't it? - </Answer> - </QA> - - <QA> - <Question> - Great! Yet-another-programming-language™. This is exactly what we need; the gazillion of - existing programming languages is not enough. - </Question> - <Answer> - Flix aims to offer a combination of features that are not found in any existing programming - language. - </Answer> - </QA> - - <QA> - <Question> - Do we really need any more programming languages? - </Question> - <Answer> - <p> - <i>Do we really need safer airplanes?</i> <i>Do we really need electric cars?</i> <i>Do we - really need more ergonomic chairs?</i> - </p> - - <p> - I mean, after all, we already have airplanes, cars, and chairs! - </p> - - <p> - We build new programming languages and we conduct research on programming language design - because we want to offer developers <i>better tools to write programs</i>. We want to make - it <i>simpler</i>, <i>safer</i>, and <i>faster</i> to write correct programs. - </p> - - <p> - And we want to increase developer happiness. It should be a pleasure to use Flix! - </p> - </Answer> - </QA> - - <QA> - <Question> - This sounds like vaporware. All big promises and no delivery. - </Question> - <Answer> - The <Link to="/research/">research</Link>, - the <a href="https://github.com/flix/flix">code</a>, - and the <a href="https://arewefast.flix.dev/">performance</a>. - </Answer> - </QA> - - <QA> - <Question> - I was disappointed to learn that Flix has feature <b>X</b> instead of my favorite - feature <b>Y</b>. - </Question> - <Answer> - We are deeply sorry to have let you down. - </Answer> - </QA> - - <QA> - <Question> - How the fuck can anyone understand such weird syntax? I hate all these symbols. - </Question> - <Answer> - <p> - The Flix syntax is <Link to="/principles/"> based on keywords</Link> except when there is a - <i>clearly established historical precedent</i> for using a symbol. For example: - </p> - - <ul> - <li>The cons of an element <code>x</code> and a list <code>xs</code> is written as <code>x - :: xs</code>. - </li> - <li>The underscore <code>_</code> denotes a wildcard (or an unused variable).</li> - <li>The expression <code><- c</code> reads a value from a channel whereas <code>c <- - v</code> writes a value to a channel. - </li> - <li>The symbol <code>:-</code> denotes logical implication in Datalog rules.</li> - </ul> - </Answer> - </QA> - - <QA> - <Question> - This is – by far – the worst syntax I have ever seen in a functional language. Semicolons, - braces, symbolic soup, et al. It is like if Scala, Java and Haskell had a one night stand in the - center of Chernobyl. - </Question> - <Answer> - Quite an achievement, wouldn't you say? - </Answer> - </QA> - - <QA> - <Question> - The examples all look horrible. The site looks horrible. This needs a lot of work before it - gets close to anything I would even consider using. - </Question> - <Answer> - Sorry, what was the question? - </Answer> - </QA> - - </Container> - ); - } + componentDidMount() { + document.title = 'Flix | FAQ' + } + + render() { + return ( + <Container> + <h1>Frequently Asked Questions</h1> + + <p className="mb-3">A collection of information that did not seem to fit in anywhere else.</p> + + <QA> + <Question>Are you looking for help with the compiler or language design?</Question> + <Answer> + Yes! We welcome any contributions and we are happy to mentor someone who wants to work on the compiler. We + are also open to general feedback and discussion about the language design. Head on over to{' '} + <a href="https://github.com/flix/flix">GitHub</a> or <a href="https://gitter.im/flix/Lobby">Gitter</a> and + reach out to us! + </Answer> + </QA> + + <QA> + <Question>Does Flix support integration with Java, Kotlin, Scala etc?</Question> + <Answer> + <p> + Yes, with the <code>import</code> mechanism. + </p> + </Answer> + </QA> + + <QA> + <Question>Flix looks quite similar to Scala. How are the two languages related?</Question> + <Answer> + <p> + Flix borrows a lot of syntax from Scala, hence the two languages have a similar feel. We think Scala made + many good design choices with respect to syntax, including: (a) the use of short keywords, (b) the{' '} + <code>x : T</code> syntax for type annotations, (c) the <code>List[Int32]</code> syntax for type + parameters, and (d) <code>if</code>, <code>match</code>, etc. as expressions. + </p> + + <p> + Other than syntax, the two languages are very different: Scala is object-oriented, Flix is not. Scala has + sub-typing, Flix does not. The Scala type system is unsound and has imperfect type inference, whereas the + Flix type system is both sound and supports type inference. + </p> + </Answer> + </QA> + + <QA> + <Question>Does Flix have a read-eval-print-loop (REPL)?</Question> + + <Answer> + No, but the compiler does have an interactive mode that can be started by passing the{' '} + <code>--interactive</code> argument. + </Answer> + </QA> + + <QA> + <Question>Does Flix have IDE support? Language Server Protocol (LSP) support?</Question> + <Answer> + Yes. There is a{' '} + <a href="https://marketplace.visualstudio.com/items?itemName=flix.flix"> + Visual Studio Code plugin available for Flix + </a> + . + </Answer> + </QA> + + <QA> + <Question>Does Flix compile to LLVM?</Question> + <Answer>No and we don't have any plans to target LLVM.</Answer> + </QA> + + <QA> + <Question>Does Flix compile to WebAssembly (WASM)?</Question> + <Answer> + No, not at the moment. It is something we are open to, but we are waiting for WebAssembly to gain a garbage + collector and tail calls. + </Answer> + </QA> + + <QA> + <Question>Why does Flix target the Java Virtual Machine (JVM)?</Question> + <Answer> + The Java Virtual Machine is a state-of-the-art virtual machine that runs on virtually every platform, comes + with a huge ecosystem of libraries, and supports garbage collection. While not the ideal target for + functional programming languages, due to its absence of tail call instructions, it is still a strong choice. + Moreover, if <a href="https://openjdk.java.net/projects/loom/">Project Loom</a> (or similar efforts) turn + out successful then the JVM will offer an unbeatable feature set. + </Answer> + </QA> + + <QA> + <Question>Is the Flix type system sound?</Question> + <Answer>Yes. It is based on Hindley-Milner.</Answer> + </QA> + + <QA> + <Question>I want to learn Flix! What should I know about before hand?</Question> + <Answer> + <p> + At the moment, Flix has not yet reached version 1.0. That means you will be an early adopter, so you + should expect for the language to evolve and be prepared for the rare compiler bug. (The Flix compiler has + 9,500 manually written tests and we take correctness seriously.) + </p> + + <p> + To write Flix programs, a solid background in functional programming is useful. That means prior + experience with OCaml, Haskell, Scala, or similar programming languages. + </p> + </Answer> + </QA> + + <QA> + <Question>What is the best way to start learning Flix?</Question> + <Answer> + <p> + We recommend that you start with a small offering to the Great Dreamer, the Sleeper of R'lyeh, Cthulhu. + And coffee. Lots of coffee. All kidding aside, the best place to start is to look at the examples and to + read the <a href="https://doc.flix.dev/">Programming Flix</a> book. + </p> + + <p>If you get stuck or need help feel free to reach out to us on Gitter.</p> + </Answer> + </QA> + + <QA> + <Question>Is Flix a domain specific language (DSL)?</Question> + <Answer> + <p>No, Flix is a full-blown functional programming language.</p> + + <p>That said, Flix could be considered a meta-programming language for Datalog.</p> + </Answer> + </QA> + + <QA> + <Question>What is the runtime performance of Flix programs?</Question> + <Answer> + <p> + Flix runs on the Java Virtual Machine (JVM) hence the performance of Flix is limited by the performance of + the JVM. Luckily, the JVM is a mature and performant virtual machine. Flix uses monomorphization which + eliminates boxing and in theory can make code execute faster than ordinary Java / Kotlin / Scala code. + However, Flix also features full tail call elimination which has some run-time performance cost. + </p> + + <p> + Our goal to be faster than any interpreted language and within a few factors of equivalent functional + Scala code. + </p> + </Answer> + </QA> + + <QA> + <Question> + Haskell and OCaml compile to native code thus – by definition – they must be faster than Flix. + </Question> + <Answer> + This is not necessarily true. For example, Java sometimes beats both{' '} + <a href="https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/ocaml-java.html">OCaml</a> and{' '} + <a href="https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/haskell.html">Haskell</a> in{' '} + <a href="https://benchmarksgame-team.pages.debian.net/benchmarksgame/index.html"> + The Computer Language Benchmarks Game + </a> + . + </Answer> + </QA> + + <QA> + <Question>What is the performance of the Flix compiler?</Question> + <Answer> + <p> + To answer this question, it is important to distinguish between{' '} + <a href="https://en.wikipedia.org/wiki/Latency_(engineering)">latency</a> and{' '} + <a href="https://en.wikipedia.org/wiki/Throughput">throughput</a>. + </p> + + <p> + The Flix compiler runs on the JVM hence startup times can be expensive, i.e. the compiler has high + latency. However, once the JVM has warmed up the compiler is quite fast, i.e. has high throughput. + </p> + + <p> + A simple experiment shows that the compiler runs about <code>20.0x</code> times faster when warmed up + compared to when cold. We estimate that Flix, when warmed up, compiles around <code>20,000</code> lines of + code per second, which we believe to be faster than the Scala compiler, but slower than the Java compiler. + We take compiler performance seriously and continuously track the{' '} + <a href="https://arewefast.flix.dev/">performance of the compiler</a>. + </p> + </Answer> + </QA> + + <QA> + <Question>Ok, but really, what is the performance of the Flix compiler?</Question> + <Answer> + <p>Compiler throughput on an Intel i5-K8600k with 16GB of RAM.</p> + + <p>Experimental results from the 30th of May 2020.</p> + + <Table striped> + <thead> + <tr> + <th className="text-center" style={{ width: '20%' }}> + Threads + </th> + <th className="text-right">Throughput (lines/sec)</th> + <th className="text-right">Ratio</th> + </tr> + </thead> + <tbody> + <tr> + <td className="text-center">1</td> + <td className="text-right">9,673</td> + <td className="text-right">1.0x</td> + </tr> + <tr> + <td className="text-center">2</td> + <td className="text-right">14,482</td> + <td className="text-right">1.5x</td> + </tr> + <tr> + <td className="text-center">3</td> + <td className="text-right">17,100</td> + <td className="text-right">1.8x</td> + </tr> + <tr> + <td className="text-center">4</td> + <td className="text-right">18,722</td> + <td className="text-right">1.9x</td> + </tr> + <tr> + <td className="text-center">5</td> + <td className="text-right">20,118</td> + <td className="text-right">2.1x</td> + </tr> + <tr> + <td className="text-center">6</td> + <td className="text-right">21,052</td> + <td className="text-right">2.2x</td> + </tr> + </tbody> + </Table> + </Answer> + </QA> + + <QA> + <Question> + What features are <i>not</i> supported by Flix? + </Question> + + <Answer> + <p> + Flix will, <i>by design</i>, not support any of the following features: + </p> + + <Table striped> + <thead> + <tr> + <th style={{ width: '20%' }}>Feature</th> + <th>Reason</th> + </tr> + </thead> + <tbody> + <tr> + <td>Exceptions</td> + <td> + Exceptions have been used to deal with two types of errors that may arise during execution of a + program: predictable errors (e.g. a file does not exist) and program bugs (e.g. stack overflow). + Flix has no exceptions. Instead, all predictable errors should be encoded as partial functions (e.g. + using <code>Option</code>) or as potentially error returning functions (e.g. using{' '} + <code>Result</code>). We are still in the process of deciding how to handle program bugs. + </td> + </tr> + <tr> + <td>Null Values</td> + <td> + Null, famously called{' '} + <a href="https://en.wikipedia.org/wiki/Tony_Hoare">Tony Hoare's billion dollar mistake</a>, is + simply a bad solution to the problem of how to represent the (potential) absence of a value. + Instead, in Flix, you should use the <code>Option</code> data type. + </td> + </tr> + <tr> + <td>Non-Total Functions</td> + <td> + The Flix standard library has been deliberately designed to avoid common programming mistakes. We + want functions that are safe and have accurate type signatures. For example, unlike Scala or + Haskell, the <code>List.head</code> function returns an <code>Option</code> since we cannot in + general guarantee that a list is non-empty. + </td> + </tr> + <tr> + <td>Silent Coercions</td> + <td> + Implicit coercions between data types (e.g. between booleans and other values or between enums and + integers) is a rich source of programming mistakes. In Flix, no type is ever converted to another + type without explicit instruction from the programmer. + </td> + </tr> + <tr> + <td>No Code Before Main</td> + <td> + In Flix, no code is ever executed before main. Flix has no static initializers (or similar + constructs) which are difficult to reason about, error-prone, and often lead to buggy code. + </td> + </tr> + <tr> + <td>Equality and Assignment Confusion</td> + <td> + In Flix, the equality test operator (<code>==</code>) is different from the assignment operator ( + <code>:=</code>) which is different from the equality sign (<code>=</code>) used in definitions and + let-bindings. Flix has been designed such that programs that mistake one for the other is unlikely + to compile. + </td> + </tr> + <tr> + <td>Undefined Behavior</td> + <td> + Undefined behavior is frequently the cause of program bugs and vulnerabilities. We want every Flix + program to have a well-defined semantics. + </td> + </tr> + </tbody> + </Table> + + <p> + This list was partially inspired by the blog post{' '} + <a href="https://graydon2.dreamwidth.org/218040.html">things rust shipped without</a>. + </p> + </Answer> + </QA> + + <QA> + <Question>What controversial design choices are made in Flix?</Question> + + <Answer> + <p>The following design choices may be considered controversial by some:</p> + + <ul> + <li>Unused variables are compile-time errors.</li> + <li>Shadowed variables are compile-time errors.</li> + <li>Unused definitions, type declarations, etc. are compile-time errors.</li> + <li>No variadic or labelled function arguments.</li> + <li>No warnings, only compile-time errors.</li> + <li> + <a href="https://www.hillelwayne.com/post/divide-by-zero/">Dividing by zero yields zero</a>. + </li> + </ul> + </Answer> + </QA> + + <QA> + <Question>Who works on Flix? Is Flix a hobby project?</Question> + <Answer> + <p> + Flix is a research project carried out by faculty and students at{' '} + <a href="http://cs.au.dk/">Aarhus University</a> and the{' '} + <a href="http://uwaterloo.ca/">University of Waterloo</a>. + </p> + + <p> + Flix is partially supported by a grant of 2,500,000 DKK from the{' '} + <a href="http://dff.dk/">Independent Research Fund of Denmark.</a> + </p> + </Answer> + </QA> + + <QA> + <Question>Where does the "Flix" name come from?</Question> + <Answer> + We do not entirely remember, but we believe it came from{' '} + <span className="text-monospace">FIXpoint Language</span>. + </Answer> + </QA> + + <QA> + <Question>Does Flix have a network library with streaming support?</Question> + <Answer>Not yet, but maybe we could call it net-flix?</Answer> + </QA> + + <QA> + <Question>You do not seem to understand parsing / type theory / code generation / computers!</Question> + <Answer> + We are happy to learn and to revisit design decisions if we come to a greater understanding of the problem + at hand. If you think we have overlooked something, we would be happy to talk about it if you post a ticket + on GitHub or write to us on Gitter. + </Answer> + </QA> + + <QA> + <Question>Why does the website require JavaScript?</Question> + <Answer> + We built the website using the popular React framework. We use JavaScript for the online code editor. Using + React was easy. Ultimately, we want to spend our time writing compilers, not writing websites. + </Answer> + </QA> + + <QA> + <Question> + The page does not load without JavaScript enabled. If I cannot even view the website without that bloat, I + wonder what the language is like? + </Question> + <Answer> + Indeed, if your computer is too old to run a modern browser that supports JavaScript then probably your + computer is too old to run a modern JVM that supports Flix. Sorry. + </Answer> + </QA> + + <QA> + <Question>It appears that an example on the website does not work?</Question> + <Answer> + <p> + The latest compiler version and the website is not always in sync, hence occasionally some examples may + stop to work. Feel free to open a bug report if this happens. + </p> + + <p> + Occasionally a mischievous visitor will crash the online editor (or rather the virtual machine on which + the compiler runs). We usually discover and fix this within a few days. + </p> + </Answer> + </QA> + + <QA> + <Question> + The language is probably great from a technical point of view, but unless Apple, Google, Mozilla, or + Microsoft is on-board it is pointless. + </Question> + <Answer> + <p> + Yes, no programming language developed outside of those four corporations have ever been successful. See + also C, C++, Java, Python, PHP, MatLab, Perl, R, Ruby, Scala, ... + </p> + + <p> + That said, if you work for a company and would like to help sponsor Flix, please feel free to reach out to + us :) + </p> + </Answer> + </QA> + + <QA> + <Question> + Wow! Amazing! A language where you can iterate through lists and call functions recursively. + </Question> + <Answer>Magical, isn't it?</Answer> + </QA> + + <QA> + <Question> + Great! Yet-another-programming-language™. This is exactly what we need; the gazillion of existing + programming languages is not enough. + </Question> + <Answer> + Flix aims to offer a combination of features that are not found in any existing programming language. + </Answer> + </QA> + + <QA> + <Question>Do we really need any more programming languages?</Question> + <Answer> + <p> + <i>Do we really need safer airplanes?</i> <i>Do we really need electric cars?</i>{' '} + <i>Do we really need more ergonomic chairs?</i> + </p> + + <p>I mean, after all, we already have airplanes, cars, and chairs!</p> + + <p> + We build new programming languages and we conduct research on programming language design because we want + to offer developers <i>better tools to write programs</i>. We want to make it <i>simpler</i>, <i>safer</i> + , and <i>faster</i> to write correct programs. + </p> + + <p>And we want to increase developer happiness. It should be a pleasure to use Flix!</p> + </Answer> + </QA> + + <QA> + <Question>This sounds like vaporware. All big promises and no delivery.</Question> + <Answer> + The <Link to="/research/">research</Link>, the <a href="https://github.com/flix/flix">code</a>, and the{' '} + <a href="https://arewefast.flix.dev/">performance</a>. + </Answer> + </QA> + + <QA> + <Question> + I was disappointed to learn that Flix has feature <b>X</b> instead of my favorite feature <b>Y</b>. + </Question> + <Answer>We are deeply sorry to have let you down.</Answer> + </QA> + + <QA> + <Question>How the fuck can anyone understand such weird syntax? I hate all these symbols.</Question> + <Answer> + <p> + The Flix syntax is <Link to="/principles/"> based on keywords</Link> except when there is a + <i>clearly established historical precedent</i> for using a symbol. For example: + </p> + + <ul> + <li> + The cons of an element <code>x</code> and a list <code>xs</code> is written as <code>x :: xs</code>. + </li> + <li> + The underscore <code>_</code> denotes a wildcard (or an unused variable). + </li> + <li> + The expression <code><- c</code> reads a value from a channel whereas <code>c <- v</code> writes a + value to a channel. + </li> + <li> + The symbol <code>:-</code> denotes logical implication in Datalog rules. + </li> + </ul> + </Answer> + </QA> + + <QA> + <Question> + This is – by far – the worst syntax I have ever seen in a functional language. Semicolons, braces, symbolic + soup, et al. It is like if Scala, Java and Haskell had a one night stand in the center of Chernobyl. + </Question> + <Answer>Quite an achievement, wouldn't you say?</Answer> + </QA> + + <QA> + <Question> + The examples all look horrible. The site looks horrible. This needs a lot of work before it gets close to + anything I would even consider using. + </Question> + <Answer>Sorry, what was the question?</Answer> + </QA> + </Container> + ) + } } class Question extends Component { - render() { - return ( - <CardTitle>{this.props.children}</CardTitle> - ); - } + render() { + return <CardTitle>{this.props.children}</CardTitle> + } } - class Answer extends Component { - render() { - return ( - <div>{this.props.children}</div> - ); - } + render() { + return <div>{this.props.children}</div> + } } class QA extends Component { - render() { - return ( - <Card className="mb-3"> - <CardBody> - {this.props.children} - </CardBody> - </Card>); - } + render() { + return ( + <Card className="mb-3"> + <CardBody>{this.props.children}</CardBody> + </Card> + ) + } } -export default Faq; +export default Faq diff --git a/src/page/GetStarted.js b/src/page/GetStarted.js index 8a775b9..bfcdf8e 100644 --- a/src/page/GetStarted.js +++ b/src/page/GetStarted.js @@ -1,77 +1,81 @@ -import React, {Component} from 'react'; -import {Card, CardImg, Col, Container, Row} from "reactstrap"; +import React, { Component } from 'react' +import { Card, CardImg, Col, Container, Row } from 'reactstrap' import VSCode from '../gif/vscode.png' class GetStarted extends Component { + componentDidMount() { + document.title = 'Flix | Getting Started' + } - componentDidMount() { - document.title = "Flix | Getting Started"; - } + render() { + return ( + <Container> + <h1>Get Started</h1> - render() { - return ( - <Container> - <h1>Get Started</h1> + <Row className="mb-4"> + <Col> + <h5>Using the Online Playground</h5> + <p> + You can try Flix online at <a href="https://play.flix.dev/">play.flix.dev</a>. + </p> + </Col> + </Row> - <Row className="mb-4"> - <Col> - <h5>Using the Online Playground</h5> - <p> - You can try Flix online at <a - href="https://play.flix.dev/">play.flix.dev</a>. - </p> - </Col> - </Row> + <hr /> - <hr/> + <Row className="mb-4"> + <Col> + <h5>Using Visual Studio Code</h5> - <Row className="mb-4"> - <Col> - <h5>Using Visual Studio Code</h5> + <p> + Or you can install Flix in <a href="https://code.visualstudio.com/">Visual Studio Code</a>: + </p> - <p> - Or you can install Flix in <a href="https://code.visualstudio.com/">Visual Studio - Code</a>: - </p> + <Card className="ml-5 mr-5"> + <CardImg top src={VSCode} /> + </Card> + </Col> + </Row> - <Card className="ml-5 mr-5"> - <CardImg top src={VSCode}/> - </Card> - </Col> - </Row> + <hr /> - <hr/> - - <Row className="mb-4"> - <Col> - <h5>Manually downloading and running the compiler</h5> - <p> - <ol> - <li>Ensure that you have at least Java 11 installed. You can check with <code>java - -version</code>. - </li> - <li>Download the latest version of the Flix compiler (<code>flix.jar</code>) at <a - href="https://github.com/flix/flix/releases/latest">https://github.com/flix/flix/releases/latest</a>. - </li> - <li>Create an empty folder (e.g. <code>mkdir flixproject</code>) and place the - downloaded Flix JAR (<code>flix.jar</code>) into that folder. - </li> - <li>Enter the created directory (e.g. <code>cd flixproject</code>) and run <code>java - -jar flix.jar init</code> to create an empty Flix project. - </li> - <li>Run <code>java -jar flix.jar run</code> to compile and run the project.</li> - <li>Flix will compile the project and execute the <code>main</code> function (located - in <code>src/Main.flix</code>). - </li> - </ol> - </p> - </Col> - </Row> - - - </Container> - ); - } + <Row className="mb-4"> + <Col> + <h5>Manually downloading and running the compiler</h5> + <p> + <ol> + <li> + Ensure that you have at least Java 11 installed. You can check with <code>java -version</code>. + </li> + <li> + Download the latest version of the Flix compiler (<code>flix.jar</code>) at{' '} + <a href="https://github.com/flix/flix/releases/latest"> + https://github.com/flix/flix/releases/latest + </a> + . + </li> + <li> + Create an empty folder (e.g. <code>mkdir flixproject</code>) and place the downloaded Flix JAR ( + <code>flix.jar</code>) into that folder. + </li> + <li> + Enter the created directory (e.g. <code>cd flixproject</code>) and run{' '} + <code>java -jar flix.jar init</code> to create an empty Flix project. + </li> + <li> + Run <code>java -jar flix.jar run</code> to compile and run the project. + </li> + <li> + Flix will compile the project and execute the <code>main</code> function (located in{' '} + <code>src/Main.flix</code>). + </li> + </ol> + </p> + </Col> + </Row> + </Container> + ) + } } -export default GetStarted; +export default GetStarted diff --git a/src/page/Home.js b/src/page/Home.js index 1aac7c0..218bf17 100644 --- a/src/page/Home.js +++ b/src/page/Home.js @@ -1,161 +1,152 @@ -import React, {Component} from 'react'; +import React, { Component } from 'react' import { - Button, - Card, - CardBody, - CardImg, - CardText, - CardTitle, - Col, - Container, - Row, - UncontrolledCarousel -} from 'reactstrap'; -import {Link} from "react-router-dom"; -import Codebox from "../util/Codebox"; -import InlineEditor from "../util/InlineEditor"; -import {Timeline} from 'react-twitter-widgets' + Button, + Card, + CardBody, + CardImg, + CardText, + CardTitle, + Col, + Container, + Row, + UncontrolledCarousel, +} from 'reactstrap' +import { Link } from 'react-router-dom' +import Codebox from '../util/Codebox' +import InlineEditor from '../util/InlineEditor' +import { Timeline } from 'react-twitter-widgets' class Home extends Component { - - componentDidMount() { - document.title = "The Flix Programming Language"; - } - - carousel = [ - { - src: '/images/vscode1.png', - caption: 'Slide 1', - header: 'VSCode: Syntax Highlighting', - }, - { - src: '/images/vscode2.png', - caption: 'Slide 2', - header: 'VSCode: Contextual Information', - }, - { - src: '/images/vscode3.png', - caption: 'Slide 3', - header: 'VSCode: Highlight References', - }, - { - src: '/images/vscode4.png', - caption: 'Slide 4', - header: 'VSCode: Inline Errors', - } - ]; - - render() { - return ( - <Container> - <Row className="mb-3"> - <Col md="6"> - <h1>The Flix Programming Language</h1> - - <h2 className="motto">Next-generation reliable, safe, concise, and functional-first programming - language.</h2> - - <p className="text-justify"> - Flix is a principled functional, imperative, and logic programming language - developed at <a href="https://cs.au.dk/">Aarhus University</a>, at the <a - href="https://uwaterloo.ca/">University of Waterloo</a>, and by a community of <a - href="https://github.com/flix/flix/graphs/contributors">open source contributors</a>. - </p> - - <p className="text-justify"> - Flix is inspired by OCaml and Haskell with ideas from Rust and Scala. Flix looks like - Scala, but its type system is based on Hindley-Milner. Two unique features - of Flix are its polymorphic effect system and its support for first-class Datalog - constraints. - </p> - - <p className="text-justify"> - Flix compiles to JVM bytecode, runs on the Java Virtual Machine, and supports full tail call - elimination. A VSCode plugin for Flix is available. - </p> - - <p> - <Button color="success" tag={Link} to="/get-started/"> - Get Started - </Button> - - <a href="https://play.flix.dev/"> - <Button color="info" className="ml-2"> - Playground - </Button> - </a> - - <Button color="info" tag={Link} to="/documentation/" className="ml-2"> - Documentation - </Button> - - <a href="https://api.flix.dev/"> - <Button color="info" className="ml-2"> - Library - </Button> - </a> - </p> - - </Col> - <Col md="6"> - <Codebox flix={this.props.flix}/> - </Col> - </Row> - - <hr className="mb-3"/> - - <Row className="mb-3"> - <Col md={12}> - - <h2>Why Flix? </h2> - - <p className="p-2 text-justify"> - Flix aims to offer a <span className="font-weight-bold text-info">unique combination of - features</span> that no other programming language offers, including: <span - className="font-weight-bold">algebraic - data types and pattern matching</span> (like Haskell, OCaml), <span - className="font-weight-bold">extensible records</span> (like Elm), <span - className="font-weight-bold">type classes</span> (like Haskell, Rust), <span - className="font-weight-bold">higher-kinded types</span> (like Haskell), <span - className="font-weight-bold">typematch</span> (like Scala), <span - className="font-weight-bold">type inference</span> (like Haskell, OCaml), <span - className="font-weight-bold">structured channel and process-based concurrency</span> (like - Go), <span - className="font-weight-bold text-success">a polymorphic effect system</span> (a unique - feature), <span - className="font-weight-bold text-success">region-based local mutation</span> (a unique - feature), <span - className="font-weight-bold text-success">purity reflection</span> (a unique - feature), <span - className="font-weight-bold text-success">first-class Datalog constraints</span> (a unique - feature), - and <span - className="font-weight-bold">compilation to JVM bytecode</span> (like Scala). - </p> - - </Col> - </Row> - - <hr className="mb-3"/> - - <Row className="mb-4"> - <Col md="6"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>Algebraic Data Types and Pattern Matching</h4></CardTitle> - <CardText> - <p> - Algebraic data types and pattern matching are the bread-and-butter of functional - programming and are supported by Flix with minimal fuss. - </p> - </CardText> - </CardBody> - </Card> - </Col> - - <Col md="6"> - <InlineEditor> - {`enum Shape { + componentDidMount() { + document.title = 'The Flix Programming Language' + } + + carousel = [ + { + src: '/images/vscode1.png', + caption: 'Slide 1', + header: 'VSCode: Syntax Highlighting', + }, + { + src: '/images/vscode2.png', + caption: 'Slide 2', + header: 'VSCode: Contextual Information', + }, + { + src: '/images/vscode3.png', + caption: 'Slide 3', + header: 'VSCode: Highlight References', + }, + { + src: '/images/vscode4.png', + caption: 'Slide 4', + header: 'VSCode: Inline Errors', + }, + ] + + render() { + return ( + <Container> + <Row className="mb-3"> + <Col md="6"> + <h1>The Flix Programming Language</h1> + + <h2 className="motto"> + Next-generation reliable, safe, concise, and functional-first programming language. + </h2> + + <p className="text-justify"> + Flix is a principled functional, imperative, and logic programming language developed at{' '} + <a href="https://cs.au.dk/">Aarhus University</a>, at the{' '} + <a href="https://uwaterloo.ca/">University of Waterloo</a>, and by a community of{' '} + <a href="https://github.com/flix/flix/graphs/contributors">open source contributors</a>. + </p> + + <p className="text-justify"> + Flix is inspired by OCaml and Haskell with ideas from Rust and Scala. Flix looks like Scala, but its type + system is based on Hindley-Milner. Two unique features of Flix are its polymorphic effect system and its + support for first-class Datalog constraints. + </p> + + <p className="text-justify"> + Flix compiles to JVM bytecode, runs on the Java Virtual Machine, and supports full tail call elimination. + A VSCode plugin for Flix is available. + </p> + + <p> + <Button color="success" tag={Link} to="/get-started/"> + Get Started + </Button> + + <a href="https://play.flix.dev/"> + <Button color="info" className="ml-2"> + Playground + </Button> + </a> + + <Button color="info" tag={Link} to="/documentation/" className="ml-2"> + Documentation + </Button> + + <a href="https://api.flix.dev/"> + <Button color="info" className="ml-2"> + Library + </Button> + </a> + </p> + </Col> + <Col md="6"> + <Codebox flix={this.props.flix} /> + </Col> + </Row> + + <hr className="mb-3" /> + + <Row className="mb-3"> + <Col md={12}> + <h2>Why Flix? </h2> + + <p className="p-2 text-justify"> + Flix aims to offer a <span className="font-weight-bold text-info">unique combination of features</span>{' '} + that no other programming language offers, including:{' '} + <span className="font-weight-bold">algebraic data types and pattern matching</span> (like Haskell, OCaml),{' '} + <span className="font-weight-bold">extensible records</span> (like Elm),{' '} + <span className="font-weight-bold">type classes</span> (like Haskell, Rust),{' '} + <span className="font-weight-bold">higher-kinded types</span> (like Haskell),{' '} + <span className="font-weight-bold">typematch</span> (like Scala),{' '} + <span className="font-weight-bold">type inference</span> (like Haskell, OCaml),{' '} + <span className="font-weight-bold">structured channel and process-based concurrency</span> (like Go),{' '} + <span className="font-weight-bold text-success">a polymorphic effect system</span> (a unique feature),{' '} + <span className="font-weight-bold text-success">region-based local mutation</span> (a unique feature),{' '} + <span className="font-weight-bold text-success">purity reflection</span> (a unique feature),{' '} + <span className="font-weight-bold text-success">first-class Datalog constraints</span> (a unique feature), + and <span className="font-weight-bold">compilation to JVM bytecode</span> (like Scala). + </p> + </Col> + </Row> + + <hr className="mb-3" /> + + <Row className="mb-4"> + <Col md="6"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>Algebraic Data Types and Pattern Matching</h4> + </CardTitle> + <CardText> + <p> + Algebraic data types and pattern matching are the bread-and-butter of functional programming and are + supported by Flix with minimal fuss. + </p> + </CardText> + </CardBody> + </Card> + </Col> + + <Col md="6"> + <InlineEditor> + {`enum Shape { case Circle(Int32), case Square(Int32), case Rectangle(Int32, Int32) @@ -166,14 +157,14 @@ def area(s: Shape): Int32 = match s { case Square(w) => w * w case Rectangle(h, w) => h * w }`} - </InlineEditor> - </Col> - </Row> + </InlineEditor> + </Col> + </Row> - <Row className="mb-4"> - <Col md="6"> - <InlineEditor> - {`def origin(): (Int32, Int32) = (0, 0) + <Row className="mb-4"> + <Col md="6"> + <InlineEditor> + {`def origin(): (Int32, Int32) = (0, 0) def oneByOne(): {w = Int32, h = Int32} = {w = 1, h = 1} @@ -183,48 +174,46 @@ def area(rect: {w = Int32, h = Int32 | r}): Int32 = rect.w * rect.h def f(): Int32 = area({h = 1, color = "Blue", w = 2})`} - </InlineEditor> - </Col> - - <Col md="6"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>Tuples and Records</h4></CardTitle> - <CardText> - <p> - Flix has built-in support for tuples and records. - </p> - - <p> - Records use structural typing and are extensible. - </p> - </CardText> - </CardBody> - </Card> - </Col> - </Row> - - <Row className="mb-4"> - <Col md="6"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>Purity and Impurity</h4></CardTitle> - <CardText> - <p> - Flix precisely tracks the purity of every expression in a program. - </p> - - <p> - The Flix compiler provides an ironclad guarantee that if an expression is pure - then it cannot have side-effects and it is referentially transparent. - </p> - </CardText> - </CardBody> - </Card> - </Col> - <Col md="6"> - <InlineEditor> - {`/// A pure function is annotated with \`\\ {}\`. + </InlineEditor> + </Col> + + <Col md="6"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>Tuples and Records</h4> + </CardTitle> + <CardText> + <p>Flix has built-in support for tuples and records.</p> + + <p>Records use structural typing and are extensible.</p> + </CardText> + </CardBody> + </Card> + </Col> + </Row> + + <Row className="mb-4"> + <Col md="6"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>Purity and Impurity</h4> + </CardTitle> + <CardText> + <p>Flix precisely tracks the purity of every expression in a program.</p> + + <p> + The Flix compiler provides an ironclad guarantee that if an expression is pure then it cannot have + side-effects and it is referentially transparent. + </p> + </CardText> + </CardBody> + </Card> + </Col> + <Col md="6"> + <InlineEditor> + {`/// A pure function is annotated with \`\\ {}\`. def inc1(x: Int32): Int32 \\ {} = x + 1 /// An impure function is annotated with \`\\ IO\`. @@ -236,14 +225,14 @@ def f(): Int32 \\ IO = // f is impure let r1 = inc1(123); // pure let r2 = inc2(456); // impure r1 + r2 // pure`} - </InlineEditor> - </Col> - </Row> - - <Row className="mb-4"> - <Col md="6"> - <InlineEditor> - {`/// + </InlineEditor> + </Col> + </Row> + + <Row className="mb-4"> + <Col md="6"> + <InlineEditor> + {`/// /// The purity of \`map\` depends on the purity of \`f\`. /// def map(f: a -> b \\ ef, l: List[a]): List[b] \\ ef = @@ -252,56 +241,57 @@ def map(f: a -> b \\ ef, l: List[a]): List[b] \\ ef = case x :: xs => f(x) :: map(f, xs) } `} - </InlineEditor> - </Col> - <Col md="6"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>Polymorphic Effects</h4></CardTitle> - <CardText> - <p> - Flix is able to track purity through higher-order effect polymorphic functions. - </p> - - <p> - For example, Flix knows that the purity of <code>List.map</code> depends on the - purity of its function argument <code>f</code>. - </p> - </CardText> - </CardBody> - </Card> - </Col> - </Row> - - <Row className="mb-4"> - <Col md="6"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>Region-based Local Mutation</h4></CardTitle> - <CardText> - <p> - Flix supports region-based local mutation, which makes it possible to - implement <i>pure</i> functions that internally uses mutable state and - destructive operations, as long as these operations are confined to the region. - </p> - - <p> - We can use local mutation when it is more natural to write a function using - mutable data and in a familiar imperative-style while still remaining pure - to the outside world. - </p> - - <p> - We can also use local mutation when it is more efficient to use mutable - data structures, e.g. when implementing a sorting algorithm. - </p> - </CardText> - </CardBody> - </Card> - </Col> - <Col md="6"> - <InlineEditor> - {`/// + </InlineEditor> + </Col> + <Col md="6"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>Polymorphic Effects</h4> + </CardTitle> + <CardText> + <p>Flix is able to track purity through higher-order effect polymorphic functions.</p> + + <p> + For example, Flix knows that the purity of <code>List.map</code> depends on the purity of its + function argument <code>f</code>. + </p> + </CardText> + </CardBody> + </Card> + </Col> + </Row> + + <Row className="mb-4"> + <Col md="6"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>Region-based Local Mutation</h4> + </CardTitle> + <CardText> + <p> + Flix supports region-based local mutation, which makes it possible to implement <i>pure</i>{' '} + functions that internally uses mutable state and destructive operations, as long as these operations + are confined to the region. + </p> + + <p> + We can use local mutation when it is more natural to write a function using mutable data and in a + familiar imperative-style while still remaining pure to the outside world. + </p> + + <p> + We can also use local mutation when it is more efficient to use mutable data structures, e.g. when + implementing a sorting algorithm. + </p> + </CardText> + </CardBody> + </Card> + </Col> + <Col md="6"> + <InlineEditor> + {`/// /// We can implement a *pure* \`sort\` function which /// internally converts an immutable list to an array, /// sorts the array in-place, and then converts it @@ -326,14 +316,14 @@ def toString(l: List[a]): String with ToString[a] = StringBuilder.toString(sb) } `} - </InlineEditor> - </Col> - </Row> - - <Row className="mb-4"> - <Col md="6"> - <InlineEditor> - {`/// + </InlineEditor> + </Col> + </Row> + + <Row className="mb-4"> + <Col md="6"> + <InlineEditor> + {`/// /// We can inspect the purity of a function argument. /// def inspect(f: a -> b \\ ef): Unit \\ IO = @@ -352,56 +342,55 @@ def map(f: a -> b \\ ef, l: LazyList[a]): LazyList[b] \\ ef = case Pure(g) => mapL(g, l) case _ => mapE(f, l) }`} - </InlineEditor> - </Col> - <Col md="6"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>Purity Reflection</h4></CardTitle> - <CardText> - <p> - Flix supports a meta-programming construct that enables higher-order functions - to inspect the purity of a function argument and use that information to vary - their behavior. - </p> - - <p> - For example, the <code>DelayList.map</code> function varies its behavior between - eager and lazy evaluation depending on the purity of its function argument. - </p> - - <p> - We can exploit purity reflection to selectively use lazy or parallel - evaluation inside a library without changing the semantics from the - point-of-view of the clients. - </p> - </CardText> - </CardBody> - </Card> - </Col> - </Row> - - <Row className="mb-4"> - <Col md="6"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>Type Classes</h4></CardTitle> - <CardText> - <p> - Flix uses type classes to abstract over types that support a common set of - operations. - </p> - <p> - For example, the <code>Eq</code> type class captures the notion of equality - and is used throughout the standard library. - </p> - </CardText> - </CardBody> - </Card> - </Col> - <Col md="6"> - <InlineEditor> - {`class Eq[a] { + </InlineEditor> + </Col> + <Col md="6"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>Purity Reflection</h4> + </CardTitle> + <CardText> + <p> + Flix supports a meta-programming construct that enables higher-order functions to inspect the purity + of a function argument and use that information to vary their behavior. + </p> + + <p> + For example, the <code>DelayList.map</code> function varies its behavior between eager and lazy + evaluation depending on the purity of its function argument. + </p> + + <p> + We can exploit purity reflection to selectively use lazy or parallel evaluation inside a library + without changing the semantics from the point-of-view of the clients. + </p> + </CardText> + </CardBody> + </Card> + </Col> + </Row> + + <Row className="mb-4"> + <Col md="6"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>Type Classes</h4> + </CardTitle> + <CardText> + <p>Flix uses type classes to abstract over types that support a common set of operations.</p> + <p> + For example, the <code>Eq</code> type class captures the notion of equality and is used throughout + the standard library. + </p> + </CardText> + </CardBody> + </Card> + </Col> + <Col md="6"> + <InlineEditor> + {`class Eq[a] { def eq(x: a, y: a): Bool def neq(x: a, y: a): Bool = not Eq.eq(x, y) } @@ -412,14 +401,14 @@ instance Eq[(a1, a2)] with Eq[a1], Eq[a2] { let (y1, y2) = t2; x1 == y1 and x2 == y2 }`} - </InlineEditor> - </Col> - </Row> + </InlineEditor> + </Col> + </Row> - <Row className="mb-4"> - <Col md="6"> - <InlineEditor> - {`class Foldable[t : Type -> Type] { + <Row className="mb-4"> + <Col md="6"> + <InlineEditor> + {`class Foldable[t : Type -> Type] { /// /// Left-associative fold of a structure. @@ -432,49 +421,51 @@ instance Eq[(a1, a2)] with Eq[a1], Eq[a2] { def foldRight(f: (a, b) -> b \\ ef, s: b, t: t[a]): b \\ ef }`} - </InlineEditor> - </Col> - <Col md="6"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>Higher-Kinded Types</h4></CardTitle> - <CardText> - <p> - Flix supports higher-kinded types making it possible to abstract over type - constructors. For example, - both <code>Option</code> and <code>List</code> implement <code>Foldable</code>. - </p> - - <p> - The Flix standard library ships with many common type classes, such - as <code>Monoid</code>, <code>Functor</code>, and <code>Foldable</code>. - </p> - </CardText> - </CardBody> - </Card> - </Col> - </Row> - - <Row className="mb-4"> - <Col md="6"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>Monadic For-Yield</h4></CardTitle> - <CardText> - <p> - Flix supports a monadic <code>forM</code>-yield construct similar to Scala's - <code>for</code>-comprehensions and Haskell's <code>do</code> notation. - The <code>forM</code> construct is syntactic sugar for uses - of <code>point</code> and <code>flatMap</code> (which are provided by the Monad - type class). - </p> - </CardText> - </CardBody> - </Card> - </Col> - <Col md="6"> - <InlineEditor> - {`def divide(x: Int32, y: Int32): Option[Int32] = + </InlineEditor> + </Col> + <Col md="6"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>Higher-Kinded Types</h4> + </CardTitle> + <CardText> + <p> + Flix supports higher-kinded types making it possible to abstract over type constructors. For + example, both <code>Option</code> and <code>List</code> implement <code>Foldable</code>. + </p> + + <p> + The Flix standard library ships with many common type classes, such as <code>Monoid</code>,{' '} + <code>Functor</code>, and <code>Foldable</code>. + </p> + </CardText> + </CardBody> + </Card> + </Col> + </Row> + + <Row className="mb-4"> + <Col md="6"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>Monadic For-Yield</h4> + </CardTitle> + <CardText> + <p> + Flix supports a monadic <code>forM</code>-yield construct similar to Scala's + <code>for</code>-comprehensions and Haskell's <code>do</code> notation. The <code>forM</code>{' '} + construct is syntactic sugar for uses of <code>point</code> and <code>flatMap</code> (which are + provided by the Monad type class). + </p> + </CardText> + </CardBody> + </Card> + </Col> + <Col md="6"> + <InlineEditor> + {`def divide(x: Int32, y: Int32): Option[Int32] = if (y == 0) None else Some(x / y) def f(): Option[Int32] = @@ -484,14 +475,14 @@ def f(): Option[Int32] = z <- divide(9, y) ) yield x + y + z `} - </InlineEditor> - </Col> - </Row> + </InlineEditor> + </Col> + </Row> - <Row className="mb-4"> - <Col md="6"> - <InlineEditor> - {`def validateUser(s: String): Validation[Err, String] = ... + <Row className="mb-4"> + <Col md="6"> + <InlineEditor> + {`def validateUser(s: String): Validation[Err, String] = ... def validatePass(s: String): Validation[Err, String] = ... @@ -501,98 +492,97 @@ def conn(u: String, p: String): Validation[Err, Connection] = pass <- validatePass(p) ) yield Connection(user, pass) `} - </InlineEditor> - </Col> - <Col md="6"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>Applicative For-Yield</h4></CardTitle> - <CardText> - <p> - In addition to the monadic <code>forM</code> expression, Flix supports an - applicative <code>forA</code> expression that builds on - the <code>Applicative</code> type class. The <code>forA</code> construct makes - it simple to write error-handling code which uses the <code>Validation[e, - t]</code> data type. - </p> - </CardText> - </CardBody> - </Card> - </Col> - </Row> - - <Row className="mb-4"> - <Col md="12"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>First-class Datalog Constraints</h4></CardTitle> - <CardText> - <p> - Another unique feature of Flix is its embedded Datalog support. Datalog, a - powerful logic programming language in its own right, makes it simple and - elegant to express many fixpoint problems (including various graph reachability - problems): - </p> - - <InlineEditor> - {`def reachable(g: List[(String, Int32, String)], minSpeed: Int32): List[(String, String)] = + </InlineEditor> + </Col> + <Col md="6"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>Applicative For-Yield</h4> + </CardTitle> + <CardText> + <p> + In addition to the monadic <code>forM</code> expression, Flix supports an applicative{' '} + <code>forA</code> expression that builds on the <code>Applicative</code> type class. The{' '} + <code>forA</code> construct makes it simple to write error-handling code which uses the{' '} + <code>Validation[e, t]</code> data type. + </p> + </CardText> + </CardBody> + </Card> + </Col> + </Row> + + <Row className="mb-4"> + <Col md="12"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>First-class Datalog Constraints</h4> + </CardTitle> + <CardText> + <p> + Another unique feature of Flix is its embedded Datalog support. Datalog, a powerful logic + programming language in its own right, makes it simple and elegant to express many fixpoint problems + (including various graph reachability problems): + </p> + + <InlineEditor> + {`def reachable(g: List[(String, Int32, String)], minSpeed: Int32): List[(String, String)] = let facts = inject g into Road; let rules = #{ Path(x, y) :- Road(x, maxSpeed, y), if maxSpeed >= minSpeed. Path(x, z) :- Path(x, y), Road(y, maxSpeed, z), if maxSpeed >= minSpeed. }; query facts, rules select (src, dst) from Path(src, dst) |> Foldable.toList`} - </InlineEditor> - - <p> - Datalog constraints are <i>first-class</i> which means that they may be passed - to and returned from functions, stored in data structures, composed with other - Datalog constraints, and solved. This makes it possible to express families of - Datalog programs. - </p> - </CardText> - </CardBody> - </Card> - </Col> - </Row> - - <Row className="mb-4"> - <Col md="6"> - <Card className="border-0"> - <CardBody> - <CardTitle><h4>Datalog Enriched with Lattice Semantics</h4></CardTitle> - <CardText> - <p> - Flix supports Datalog constraints enriched with lattice semantics. - </p> - - <p> - The program on the right computes the delivery date for a collection of - parts. Each part is assembled from a collection of sub-components with various - delivery dates. For example, a car depends on a chassis and an engine. To build - a car, we need to wait for the chassis and engine to assembled and then we can - assemble the car itself. - </p> - - <p> - Note that parts may depend on sub-components that themselves may depend on other - sub-components. In other words, the problem is recursive. - </p> - - <hr/> - - <p> - Datalog constraints enriched with lattice semantics is one of the more - advanced features of Flix and requires some background knowledge of lattice - theory and fixpoints. - </p> - </CardText> - </CardBody> - </Card> - </Col> - <Col md="6"> - <InlineEditor> - {`let p = #{ + </InlineEditor> + + <p> + Datalog constraints are <i>first-class</i> which means that they may be passed to and returned from + functions, stored in data structures, composed with other Datalog constraints, and solved. This + makes it possible to express families of Datalog programs. + </p> + </CardText> + </CardBody> + </Card> + </Col> + </Row> + + <Row className="mb-4"> + <Col md="6"> + <Card className="border-0"> + <CardBody> + <CardTitle> + <h4>Datalog Enriched with Lattice Semantics</h4> + </CardTitle> + <CardText> + <p>Flix supports Datalog constraints enriched with lattice semantics.</p> + + <p> + The program on the right computes the delivery date for a collection of parts. Each part is + assembled from a collection of sub-components with various delivery dates. For example, a car + depends on a chassis and an engine. To build a car, we need to wait for the chassis and engine to + assembled and then we can assemble the car itself. + </p> + + <p> + Note that parts may depend on sub-components that themselves may depend on other sub-components. In + other words, the problem is recursive. + </p> + + <hr /> + + <p> + Datalog constraints enriched with lattice semantics is one of the more advanced features of Flix and + requires some background knowledge of lattice theory and fixpoints. + </p> + </CardText> + </CardBody> + </Card> + </Col> + <Col md="6"> + <InlineEditor> + {`let p = #{ /// Parts and the components they depend on. PartDepends("Car", "Chassis"). PartDepends("Car", "Engine"). @@ -622,180 +612,173 @@ def conn(u: String, p: String): Validation[Err, Connection] = // Computes the delivery date for each component. let r = query p select (c, d) from ReadyDate(c; d) `} - </InlineEditor> - </Col> - </Row> - - <hr className="mb-3"/> - - <Row className="mb-3"> - <Col md="12"> - <h2>Complete Feature List</h2> - </Col> - <Col md="4"> - <ul> - <li>algebraic data types</li> - <li>pattern matching</li> - <li>first-class functions</li> - <li>extensible records</li> - <li>parametric polymorphism</li> - <li>type classes</li> - <li>higher-kinded types</li> - <li>light-weight polymorphic effects</li> - <li>type aliases</li> - <li>Hindley-Milner type inference</li> - </ul> - </Col> - - <Col md="4"> - <ul> - <li>CSP-style concurrency</li> - <li>buffered & unbuffered channels</li> - <li>first-class datalog constraints</li> - <li>polymorphic datalog predicates</li> - <li>constraints with lattice semantics</li> - <li>stratified negation</li> - <li>interoperability with Java</li> - <li>unboxed primitives</li> - <li>keyword-based syntax</li> - <li>redundancy checks</li> - </ul> - </Col> - - <Col md="4"> - <ul> - <li>monadic forM expressions</li> - <li>applicative forA expressions</li> - <li>expressions holes</li> - <li>compilation to JVM bytecode</li> - <li>full tail call elimination</li> - <li>core standard library</li> - <li>parallel compiler architecture</li> - <li>human friendly errors</li> - <li>interactive mode</li> - <li>Visual Studio Code support</li> - </ul> - </Col> - </Row> - - <hr className="mb-3"/> - - <Row className="mb-3"> - <Col md={12}> - <h2>Visual Studio Code Support</h2> - - <p> - The Flix compiler integrates with Visual Studio Code providing a richer development - experience: - </p> - - <UncontrolledCarousel autoPlay={false} items={this.carousel} className="ml-2 mr-2"/> - </Col> - </Row> - - <hr className="mb-3"/> - - <Row className="mb-4"> - <Col md={6}> - <Card className="mb-4"> - <CardBody> - <CardTitle>Principled Design</CardTitle> - <CardText className="text-justify"> - It is our goal to build Flix on a solid foundation of ideas from programming - language research. We aim to identify and document a collection of design - principles. We try to adopt great and proven ideas from other programming languages - such as F#, Go, OCaml, Haskell, Rust, and Scala. - </CardText> - </CardBody> - </Card> - - <Card> - <CardBody> - <CardTitle>Visual Studio Code Support</CardTitle> - <CardText className="text-justify"> - Flix supports integration with Visual Studio Code through LSP. This includes support - for features such as: inline compiler errors, hover to show the type and effect of - an expression, jump to definition, find all usages of local variables, functions, - algebraic data types, and rename support. - </CardText> - </CardBody> - </Card> - </Col> - - <Col md={6}> - <Timeline - dataSource={{ - sourceType: 'profile', - screenName: 'flixlang' - }} - options={{ - chrome: "nofooter", - height: '430', - dnt: true - }} - /> - </Col> - </Row> - - <hr className="mb-3"/> - - <Row className="mb-3"> - <Col md="12"> - <h2>Sponsors, Funding, and Collaborations</h2> - </Col> - - <Col> - <Card className="border-0 p-3"> - <CardImg src="/logo/dff.png" alt="Independent Research Fund Denmark"/> - </Card> - </Col> - <Col> - <Card className="border-0 p-3"> - <CardImg src="/logo/direc.png" alt="Digital Research Centre Denmark"/> - </Card> - </Col> - <Col> - <Card className="border-0 p-3"> - <CardImg src="/logo/amazon-science.png" alt="Amazon Research Award"/> - </Card> - </Col> - <Col> - <Card className="border-0 p-3"> - <CardImg src="/logo/stibo.png" alt="StiboFonden"/> - </Card> - </Col> - </Row> - - <Row> - <Col> - <Card className="border-0 p-3"> - <CardImg src="/logo/aarhusu.png" alt="Aarhus University"/> - </Card> - </Col> - <Col> - <Card className="border-0 p-3"> - <CardImg src="/logo/uwaterloo.png" alt="University of Waterloo"/> - </Card> - </Col> - </Row> - - <hr className="mb-3"/> - - <Row className="mb-3 pb-3"> - <Col xs="12"> - <p className="small float-right"> - We kindly thank <a href="https://www.ej-technologies.com/">EJ Technologies</a> for providing - us with <a - href="https://www.ej-technologies.com/products/jprofiler/overview.html">JProfiler</a> and <a - href="https://www.jetbrains.com/">JetBrains</a> for providing us with <a - href="https://www.jetbrains.com/idea/">IntelliJ IDEA</a>. - </p> - </Col> - </Row> - - </Container> - ); - } + </InlineEditor> + </Col> + </Row> + + <hr className="mb-3" /> + + <Row className="mb-3"> + <Col md="12"> + <h2>Complete Feature List</h2> + </Col> + <Col md="4"> + <ul> + <li>algebraic data types</li> + <li>pattern matching</li> + <li>first-class functions</li> + <li>extensible records</li> + <li>parametric polymorphism</li> + <li>type classes</li> + <li>higher-kinded types</li> + <li>light-weight polymorphic effects</li> + <li>type aliases</li> + <li>Hindley-Milner type inference</li> + </ul> + </Col> + + <Col md="4"> + <ul> + <li>CSP-style concurrency</li> + <li>buffered & unbuffered channels</li> + <li>first-class datalog constraints</li> + <li>polymorphic datalog predicates</li> + <li>constraints with lattice semantics</li> + <li>stratified negation</li> + <li>interoperability with Java</li> + <li>unboxed primitives</li> + <li>keyword-based syntax</li> + <li>redundancy checks</li> + </ul> + </Col> + + <Col md="4"> + <ul> + <li>monadic forM expressions</li> + <li>applicative forA expressions</li> + <li>expressions holes</li> + <li>compilation to JVM bytecode</li> + <li>full tail call elimination</li> + <li>core standard library</li> + <li>parallel compiler architecture</li> + <li>human friendly errors</li> + <li>interactive mode</li> + <li>Visual Studio Code support</li> + </ul> + </Col> + </Row> + + <hr className="mb-3" /> + + <Row className="mb-3"> + <Col md={12}> + <h2>Visual Studio Code Support</h2> + + <p>The Flix compiler integrates with Visual Studio Code providing a richer development experience:</p> + + <UncontrolledCarousel autoPlay={false} items={this.carousel} className="ml-2 mr-2" /> + </Col> + </Row> + + <hr className="mb-3" /> + + <Row className="mb-4"> + <Col md={6}> + <Card className="mb-4"> + <CardBody> + <CardTitle>Principled Design</CardTitle> + <CardText className="text-justify"> + It is our goal to build Flix on a solid foundation of ideas from programming language research. We aim + to identify and document a collection of design principles. We try to adopt great and proven ideas + from other programming languages such as F#, Go, OCaml, Haskell, Rust, and Scala. + </CardText> + </CardBody> + </Card> + + <Card> + <CardBody> + <CardTitle>Visual Studio Code Support</CardTitle> + <CardText className="text-justify"> + Flix supports integration with Visual Studio Code through LSP. This includes support for features such + as: inline compiler errors, hover to show the type and effect of an expression, jump to definition, + find all usages of local variables, functions, algebraic data types, and rename support. + </CardText> + </CardBody> + </Card> + </Col> + + <Col md={6}> + <Timeline + dataSource={{ + sourceType: 'profile', + screenName: 'flixlang', + }} + options={{ + chrome: 'nofooter', + height: '430', + dnt: true, + }} + /> + </Col> + </Row> + + <hr className="mb-3" /> + + <Row className="mb-3"> + <Col md="12"> + <h2>Sponsors, Funding, and Collaborations</h2> + </Col> + + <Col> + <Card className="border-0 p-3"> + <CardImg src="/logo/dff.png" alt="Independent Research Fund Denmark" /> + </Card> + </Col> + <Col> + <Card className="border-0 p-3"> + <CardImg src="/logo/direc.png" alt="Digital Research Centre Denmark" /> + </Card> + </Col> + <Col> + <Card className="border-0 p-3"> + <CardImg src="/logo/amazon-science.png" alt="Amazon Research Award" /> + </Card> + </Col> + <Col> + <Card className="border-0 p-3"> + <CardImg src="/logo/stibo.png" alt="StiboFonden" /> + </Card> + </Col> + </Row> + + <Row> + <Col> + <Card className="border-0 p-3"> + <CardImg src="/logo/aarhusu.png" alt="Aarhus University" /> + </Card> + </Col> + <Col> + <Card className="border-0 p-3"> + <CardImg src="/logo/uwaterloo.png" alt="University of Waterloo" /> + </Card> + </Col> + </Row> + + <hr className="mb-3" /> + + <Row className="mb-3 pb-3"> + <Col xs="12"> + <p className="small float-right"> + We kindly thank <a href="https://www.ej-technologies.com/">EJ Technologies</a> for providing us with{' '} + <a href="https://www.ej-technologies.com/products/jprofiler/overview.html">JProfiler</a> and{' '} + <a href="https://www.jetbrains.com/">JetBrains</a> for providing us with{' '} + <a href="https://www.jetbrains.com/idea/">IntelliJ IDEA</a>. + </p> + </Col> + </Row> + </Container> + ) + } } -export default Home; +export default Home diff --git a/src/page/Internships.js b/src/page/Internships.js index b80854c..fc73a14 100644 --- a/src/page/Internships.js +++ b/src/page/Internships.js @@ -1,63 +1,58 @@ -import React, {Component} from 'react'; -import {Col, Container, Row} from "reactstrap"; +import React, { Component } from 'react' +import { Col, Container, Row } from 'reactstrap' class Internships extends Component { - - componentDidMount() { - document.title = "Flix | Internships"; - } - - render() { - return (<Container> - <Row className="mb-3"> - <Col> - - <h1>Research Internships</h1> - - <p className="font-weight-bold mt-4 mb-4"> - Interested in programming language research? - Want to work on compilers? - Want to work on Flix? - </p> - - <p> - Then join us for a research internship at Aarhus University in Denmark! - </p> - - <hr/> - - <p> - To apply, send an email to <code>magnusm at cs dot au dot dk</code> with a bit of - information about yourself. - </p> - - <p> - A typical research internship lasts 6-8 weeks in the summer period (but other times of year - may also be possible). - </p> - - <hr/> - - <p> - Aarhus University will reimburse travel and visa costs for coming to Denmark. - In addition, it is possible to apply for a small stipend to help cover housing and living - expenses. - </p> - - <p> - To apply, you should be enrolled in a bachelor's or master's degree programme at an accredited - university. You should have taken one or two courses on programming languages and on compilers - (exceptions can be made for especially talented students.) - </p> - - <p> - If you have questions, feel free to head over to <a - href="https://gitter.im/flix/Lobby">Gitter</a> and talk to us. - </p> - </Col> - </Row> - </Container>); - } + componentDidMount() { + document.title = 'Flix | Internships' + } + + render() { + return ( + <Container> + <Row className="mb-3"> + <Col> + <h1>Research Internships</h1> + + <p className="font-weight-bold mt-4 mb-4"> + Interested in programming language research? Want to work on compilers? Want to work on Flix? + </p> + + <p>Then join us for a research internship at Aarhus University in Denmark!</p> + + <hr /> + + <p> + To apply, send an email to <code>magnusm at cs dot au dot dk</code> with a bit of information about + yourself. + </p> + + <p> + A typical research internship lasts 6-8 weeks in the summer period (but other times of year may also be + possible). + </p> + + <hr /> + + <p> + Aarhus University will reimburse travel and visa costs for coming to Denmark. In addition, it is possible + to apply for a small stipend to help cover housing and living expenses. + </p> + + <p> + To apply, you should be enrolled in a bachelor's or master's degree programme at an accredited university. + You should have taken one or two courses on programming languages and on compilers (exceptions can be made + for especially talented students.) + </p> + + <p> + If you have questions, feel free to head over to <a href="https://gitter.im/flix/Lobby">Gitter</a> and + talk to us. + </p> + </Col> + </Row> + </Container> + ) + } } -export default Internships; +export default Internships diff --git a/src/page/Koans.js b/src/page/Koans.js index cde7fd0..10bbf06 100644 --- a/src/page/Koans.js +++ b/src/page/Koans.js @@ -1,61 +1,55 @@ -import React, {Component} from "react"; -import {Col, Container, Row} from "reactstrap"; -import InlineEditor from "../util/InlineEditor"; +import React, { Component } from 'react' +import { Col, Container, Row } from 'reactstrap' +import InlineEditor from '../util/InlineEditor' class Koans extends Component { - - componentDidMount() { - document.title = "Flix | Koans"; - } - - render() { - return ( - <Container style={{"text-align": "justify"}}> - <Row className="mb-3"> - <Col> - <h1>Flix Koans</h1> - - <p> - <i>Koan</i> — A paradox to be meditated upon that is used to train Zen Buddhist monks - to abandon ultimate dependence on reason and to force them into gaining sudden intuitive - enlightenment. - </p> - - <h5> - Given a road network, determine if it is possible to drive from one city to another city. - </h5> - - <InlineEditor> - {`pub def drivable(roads: Array[(city, city)], source: city, destination: city): Bool with Boxable[city] = + componentDidMount() { + document.title = 'Flix | Koans' + } + + render() { + return ( + <Container style={{ 'text-align': 'justify' }}> + <Row className="mb-3"> + <Col> + <h1>Flix Koans</h1> + + <p> + <i>Koan</i> — A paradox to be meditated upon that is used to train Zen Buddhist monks to abandon + ultimate dependence on reason and to force them into gaining sudden intuitive enlightenment. + </p> + + <h5>Given a road network, determine if it is possible to drive from one city to another city.</h5> + + <InlineEditor> + {`pub def drivable(roads: Array[(city, city)], source: city, destination: city): Bool with Boxable[city] = let r = project roads into Road; let lp = #{ Path(x, y) :- Road(x, y). Path(x, z) :- Path(x, y), Road(y, z). }; not Array.isEmpty(query r, lp select () from Path(source, destination))`} - </InlineEditor> + </InlineEditor> - <h5> - Given a road network with speed limits on each road, determine if it is possible to drive - from one city to another city going at least a certain speed. - </h5> + <h5> + Given a road network with speed limits on each road, determine if it is possible to drive from one city to + another city going at least a certain speed. + </h5> - <InlineEditor> - {`pub def drivable(roads: Array[(city, Int32, city)], source: city, destination: city, minimumSpeed: Int32): Bool with Boxable[city] = + <InlineEditor> + {`pub def drivable(roads: Array[(city, Int32, city)], source: city, destination: city, minimumSpeed: Int32): Bool with Boxable[city] = let r = project roads into Road; let lp = #{ Path(x, y) :- Road(x, maximumSpeed, y), if maximumSpeed > minimumSpeed. Path(x, z) :- Path(x, y), Road(y, maximumSpeed, z), if maximumSpeed > minimumSpeed. }; not Array.isEmpty(query r, lp select () from Path(source, destination))`} - </InlineEditor> + </InlineEditor> - <h5> - Given a road network, compute all pairs of cities that are not connected by roads. - </h5> + <h5>Given a road network, compute all pairs of cities that are not connected by roads.</h5> - <InlineEditor> - {`pub def unconnected(roads: Array[(city, city)]): Array[(city, city)] with Boxable[city] = + <InlineEditor> + {`pub def unconnected(roads: Array[(city, city)]): Array[(city, city)] with Boxable[city] = let r = project roads into Road; let lp = #{ City(x) :- Road(x, _). @@ -65,15 +59,15 @@ class Koans extends Component { Unconnected(x, y) :- City(x), City(y), not Path(x, y). }; query r, lp select (x, y) from Unconnected(x, y)`} - </InlineEditor> + </InlineEditor> - <h5> - Given a train and a bus network, compute if there is a path from one city to another city - with at most the given maximum number of bus connections. - </h5> + <h5> + Given a train and a bus network, compute if there is a path from one city to another city with at most the + given maximum number of bus connections. + </h5> - <InlineEditor> - {`pub def travelWithLimitedBusses(trainConnections: Array[(city, city)], busConnections: Array[(city, city)], source: city, destination: city, maxBusTrips: Int32): Bool with Boxable[city] = + <InlineEditor> + {`pub def travelWithLimitedBusses(trainConnections: Array[(city, city)], busConnections: Array[(city, city)], source: city, destination: city, maxBusTrips: Int32): Bool with Boxable[city] = let tc = project trainConnections into Train; let bc = project busConnections into Bus; let lp = #{ @@ -84,28 +78,24 @@ class Koans extends Component { }; let possibleBusTrips = query tc, bc, lp select busses from Path(source, busses, destination) where busses <= maxBusTrips; possibleBusTrips.length > 0`} - </InlineEditor> + </InlineEditor> - <h5> - Given a family tree, compute the pairs of half siblings. - </h5> + <h5>Given a family tree, compute the pairs of half siblings.</h5> - <InlineEditor> - {`pub def halfSiblings(siblings: Array[(person, person)]): Array[(person, person)] with Boxable[person] = + <InlineEditor> + {`pub def halfSiblings(siblings: Array[(person, person)]): Array[(person, person)] with Boxable[person] = let s = project siblings into Sibling; let lp = #{ Sibling(x, y) :- Parent(x, p), Parent(y, p), if x != y. HalfSibling(x, y) :- Sibling(x, y), Parent(y, p), not Parent(x, p). }; query s, lp select (x, y) from HalfSibling(x, y)`} - </InlineEditor> + </InlineEditor> - <h5> - Given a family tree of Roman emperors, compute the heir of every emperor and every usurper. - </h5> + <h5>Given a family tree of Roman emperors, compute the heir of every emperor and every usurper.</h5> - <InlineEditor> - {`pub def heirsAndUsurpers(parents: Array[(person, person)], emperors: Array[person]): {heirs = Array[person], usurpers = Array[person]} with Boxable[person] = + <InlineEditor> + {`pub def heirsAndUsurpers(parents: Array[(person, person)], emperors: Array[person]): {heirs = Array[person], usurpers = Array[person]} with Boxable[person] = let p = project parents into Parent; let e = project emperors into Emperor; let lp = #{ @@ -120,16 +110,15 @@ class Koans extends Component { let heirs = query solution select x from Heir(x); let usurpers = query solution select x from Usurper(x); {heirs = heirs, usurpers = usurpers}`} - </InlineEditor> + </InlineEditor> - <h5> - Given a social network graph, compute a collection of friend suggestions. A person is a - possible friend if he or she is not (yet) my friend and is friends with at least three of my - current friends. - </h5> + <h5> + Given a social network graph, compute a collection of friend suggestions. A person is a possible friend if + he or she is not (yet) my friend and is friends with at least three of my current friends. + </h5> - <InlineEditor> - {`pub def friendSuggestions(friends: Array[(person, person)]): Array[(person, person)] with Boxable[person] = + <InlineEditor> + {`pub def friendSuggestions(friends: Array[(person, person)]): Array[(person, person)] with Boxable[person] = let f = project friends into Friend; let lp = #{ Suggestion(me, nf) :- @@ -139,19 +128,17 @@ class Koans extends Component { if f1 != f2 and f2 != f3 and f1 != f3. }; query f, lp select (x, y) from Suggestion(x, y)`} - </InlineEditor> + </InlineEditor> - <h5> - Given a list of operating system processes, compute all orphaned and zombie processes. - </h5> + <h5>Given a list of operating system processes, compute all orphaned and zombie processes.</h5> - <p> - An <i>orphaned process</i> has no parent or has <i>init</i> (pid 1) as its parent. A <i>zombie - process</i> is dead, but its parent is still alive. - </p> + <p> + An <i>orphaned process</i> has no parent or has <i>init</i> (pid 1) as its parent. A <i>zombie process</i>{' '} + is dead, but its parent is still alive. + </p> - <InlineEditor> - {`pub def orphansAndZombies(processes: Array[(processId, String, processId)], rootId: processId): {orphans = Array[processId], zombies = Array[processId]} with Boxable[processId] = + <InlineEditor> + {`pub def orphansAndZombies(processes: Array[(processId, String, processId)], rootId: processId): {orphans = Array[processId], zombies = Array[processId]} with Boxable[processId] = let p = project processes into Process; let lp = #{ Zombie(pid) :- Process(pid, "dead", parent), Process(parent, "alive", _). @@ -163,14 +150,12 @@ class Koans extends Component { let zombies = query solution select pid from Zombie(pid); let orphans = query solution select pid from Orphan(pid); {zombies = zombies, orphans = orphans}`} - </InlineEditor> + </InlineEditor> - <h5> - Given a list of graphs, find all pairs of graphs whose union is acyclic. - </h5> + <h5>Given a list of graphs, find all pairs of graphs whose union is acyclic.</h5> - <InlineEditor> - {`def isCyclic(edges: Array[(Int32, Int32)]): Bool = + <InlineEditor> + {`def isCyclic(edges: Array[(Int32, Int32)]): Bool = let e = project edges into Edge; let lp = #{ Path(x, y) :- Edge(x, y). @@ -184,12 +169,12 @@ class Koans extends Component { pub def pairwiseAcyclic(graphs: List[Array[(Int32, Int32)]]): List[List[Array[(Int32, Int32)]]] = let combineGraphs = (g1, g2) -> query (project g1 into Edge) <+> (project g2 into Edge) select (x, y) from Edge(x, y); graphs |> List.groupBy((g1, g2) -> not isCyclic(combineGraphs(g1, g2)))`} - </InlineEditor> - - </Col> - </Row> - </Container>); - } + </InlineEditor> + </Col> + </Row> + </Container> + ) + } } -export default Koans; +export default Koans diff --git a/src/page/Principles.js b/src/page/Principles.js index 7216f07..74fac70 100644 --- a/src/page/Principles.js +++ b/src/page/Principles.js @@ -1,622 +1,565 @@ -import React, {Component} from 'react'; -import {Badge, Card, CardBody, CardColumns, CardTitle, Container} from 'reactstrap'; +import React, { Component } from 'react' +import { Badge, Card, CardBody, CardColumns, CardTitle, Container } from 'reactstrap' class Principles extends Component { - - componentDidMount() { - document.title = "Flix | Principles"; - } - - render() { - return ( - <Container> - <h1>Design Principles</h1> - - <p className="mb-3"> - We believe that the development of a programming language should follow a set of principles. - That is, when a design decision is made there should exist some rationale for why that - decision was made. By outlining these principles, as we develop Flix, we hope to keep ourselves - honest and to communicate the kind of language Flix aspires to be. - </p> - - <p className="mb-3"> - Many of these ideas and principles come from languages that have inspired Flix, including Ada, Elm, - F#, Go, Haskell, OCaml, Rust, and Scala. - </p> - - <p> - <b>Update:</b> The Flix Principles has been published in a paper at Onward! '22. Read it here: <a - href="https://dl.acm.org/doi/10.1145/3563835.3567661">The Principles of the Flix Programming - Language</a>. - </p> - - <h2 className="mt-3">Language Principles</h2> - - <CardColumns> - - <Principle name="Simple is not easy"> - We believe in Rich Hickey's creed: <a - href="https://www.infoq.com/presentations/Simple-Made-Easy">simple - is not easy</a>. We prefer a language that gets things right to one that makes things - easy. Such a language might take longer to learn in the short run, but its simplicity pays off - in the long run. - </Principle> - - <Principle name="Everything is an expression"> - Flix is a functional language and embraces the idea that everything should be an expression. - Flix has no local variable declarations or if-then-else statements, instead it has - let-bindings and if-then-else expressions. - - However, Flix does not take this idea as far as the Scheme languages. Flix still has - declarations, namespaces, and so forth that are not expressions. - </Principle> - - <Principle name="Separate pure and impure code"> - Flix supports functional, imperative, and logic programming. The type and effect system of Flix - cleanly and safely separates pure code from impure code. That is, if a function is pure then the - programmer can trust that the function behaves like a mathematical function: it returns the same - value when given the same arguments and it has no side-effects. - </Principle> - - <Principle name="Developer productivity over runtime performance"> - Flix aims to support developer productivity; the ability to do a lot with little ceremony or - boilerplate. A hand-crafted C program might run faster than a Flix program, but it won't be as - short, concise, or expressive as the Flix program. Flix aims to be a language with powerful - constructs and high-level abstractions. This does not mean that Flix is slow. - </Principle> - - <Principle name="Correctness over performance"> - Flix aims to ensure program correctness and considers it more important than raw performance. - Languages such as C and C++ often rely on undefined behaviour to achieve stellar performance, - whereas most other languages, including Flix, try to eschew undefined behaviour in favor of - runtime checks for things that are hard to statically ensure. For example, most languages will - dynamically check that array accesses are not out of bounds. The cost is a small performance - hit, but in our view the benefit towards correctness is immense. Inspired by Ada, Flix aims to - offer strong guarantees, ideally ensured statically, but when necessary with dynamic checks. - </Principle> - - <Principle name="One language"> - Flix is <i>one</i> programming language. The Flix compiler does not have feature flags or - compiler plugins that change or extend the semantics of the language. We want to avoid - fragmentation in the ecosystem where programs end up being written in different "dialects" of - the language. There is one language, now and forever. Of course that does not imply that the - language will not evolve over time. - </Principle> - - <Principle name="Principle of least surprise"> - We should strive to adhere to the <a - href="https://en.wikipedia.org/wiki/Principle_of_least_astonishment">principle of least - surprise</a>. That is, we should favor sane defaults, and when there is no immediately obvious - default, we should not have a default at all, but force the programmer to be explicit about his - or her intention. - </Principle> - - <Principle name="Local type inference"> - The Flix type system is based on <a - href="https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system">Hindley-Milner</a> which - supports full type inference. As a design choice, we require all functions to be annotated with - their argument and return types. We believe that requiring type signatures has three distinct - advantages that outweigh the disadvantages. - <ol> - <li>Type signatures are useful as documentation and to aid program understanding.</li> - <li>Type signatures accurately assign blame for type errors.</li> - <li>Type signatures enable parallel type checking.</li> - </ol> - Of these, we think the former two are significantly more important than the latter. - </Principle> - - <Principle name="Type parameter elision"> - While we require type signatures, we also believe that such signatures should be as minimal - as possible. Thus, while the full type signature of <code>List.map</code> is <code>def map[a, - b](f: a -{'>'} b, xs: List[a]): List[b]</code>, we can use <i>type parameter elision</i> to - write it - simply as: <code>def map(f: a -{'>'} b, xs: List[a]): List[b]</code> omitting the type - arguments. - </Principle> - - <Principle name="Syntax vs. Semantics"> - Syntax is important. Semantics are important. But we should not confuse the two. A syntactic - issue should not be resolved by a enrichment of the semantics. For example, <a - href=" https://en.wikipedia.org/wiki/Extension_method">extension methods</a> and <a - href="https://docs.scala-lang.org/overviews/core/implicit-classes.html">implicit - classes</a> seem to be semantic solutions to (mostly) syntactic issues. Flix aims to avoid such - pitfalls. - </Principle> - - <Principle name="Keyword-based syntax"> - The Flix syntax is inspired by Scala. We believe that short key words make it - easy to visually identify the overall structure of a piece of code. Flix tries to use - three letter keywords where appropriate: <code>def</code>, <code>let</code>, <code>law</code>, - <code>rel</code>, but not for commonly established concepts: <code>if ... else </code> - and <code>match</code>. - </Principle> - - <Principle name="Consistent syntax"> - Flix aims to have consistent and predictable syntax. As an example, we try to have the - syntax of types mirror that of expressions: - <ul> - <li> - A function application is written as <code>f(a, b, c)</code> whereas a type application - is written as <code>f[a, b, c]</code>. - </li> - <li> - A function expression is written as <code>x -> x + 1</code> whereas a function type - is written as <code>Int -> Int</code>. - </li> - <li> - A tuple is written as <code>(true, 12345)</code> whereas a tuple type - is written as <code>(Bool, Int)</code>. - </li> - </ul> - </Principle> - - <Principle name="Human-readable errors"> - In the spirit of <a href="https://elm-lang.org/blog/compilers-as-assistants">Elm</a> and <a - href="https://blog.rust-lang.org/2016/08/10/Shape-of-errors-to-come.html">Rust</a>, - Flix aims to have human readable and understandable compiler messages. - Messages should describe the problem in - detail and provide information about the context, including suggestions for how to correct - the problem. - </Principle> - - <Principle name="Private by default"> - Flix embraces the principle of least privilege. In Flix, declarations are hidden by default - (i.e. private) and cannot be accessed from outside of their namespace (or - sub-namespaces). - We believe it is important that programmers are forced to make a conscious - choice about when to make a declaration publicly visible. - </Principle> - - <Principle name="Closed world assumption"> - Flix requires all code to be available at compile-time. This enables a range of - compilation techniques, such as: - - <ul> - <li>Monomorphization to avoid unnecessary boxing of primitives.</li> - <li>Aggressive dead code elimination ("tree shaking") to remove unused functions.</li> - <li>Inlining across namespaces.</li> - <li>Whole-program analysis.</li> - </ul> - </Principle> - - <Principle name="Illegal states should be unrepresentable"> - We believe that a language should make it easy to make illegal states unrepresentable. - For example, algebraic data types can be used to precisely define the possible values of a type. - In Flix, in the future, we want to take this a step further, and allow refinement of some types. - For example, to express that some value must not only be an integer, but also that it must - fall within a range, e.g. <code>[0-99]</code>. - <br/> - <Badge>in progress</Badge> - </Principle> - - <Principle name="Nothing is executed before main"> - In Flix, <code>main</code> is the entry point of a program. - No (user-defined) code is ever executed before <code>main</code>. - No static initializers, no static fields. No class loaders. Main is always first. - This makes it easy to reason about startup behavior. - </Principle> - - <Principle name="Small, but comprehensive standard library"> - Flix has a small standard library with a few common data types, - e.g. <code>Option</code>, <code>List</code>, <code>Set</code>, - and <code>Map</code>, but for these it offers a comprehensive collection of functionality. - For example, the standard library has more than 65 functions for working with lists. - We want the standard library to offer a common set of abstractions which are usable - by most programs, but not much else. - </Principle> - - <Principle name="Declare before use"> - In Flix things must be defined before they can be used. - Algebraic data types, functions, local variables, and other programming elements must be - declared before they can be used by other program parts. Declarations make it easy to assign - blame; we assume declarations to be correct and check every use against its declaration. - For example, an algebraic data type declares a set of cases, and the compiler checks that - every use refers to one of these cases, and that every case is covered. - </Principle> - - <Principle name="No unnecessary declarations"> - We believe that a programming language should reduce the volume of declarations - it <i>requires</i>. Declarations may be useful and are sometimes necessary, but Flix aims to - minimize its internal dependence on them. To give an example, Flix supports <i>extensible - records</i> which permits the usage of flexible and type-safe records <i>without</i> a strict - requirement that record types must be declared upfront. - </Principle> - - <Principle name="No global state"> - In Flix there is no global shared state. - This avoids a plethora of issues, including difficulties with initialization order and race - conditions in the presence of concurrency. A Flix programmer is free to construct some - state in the main function and pass it around, but there is no built-in mechanism to declare - global variables. In a real system, the programmer still has to deal with the state of - the world, e.g. the state of the file system, the network, and other resources. - </Principle> - - <Principle name="Share memory by communicating"> - Flix follows the Go mantra: <a href="https://blog.golang.org/share-memory-by-communicating"><i>Do - not communicate by sharing memory; instead, share memory by - communicating.</i></a> In other words: mutable memory should never be shared between processes. - Processes should only share immutable messages (and data structures). We believe this - significantly reduces the risk of <a href="https://en.wikipedia.org/wiki/Race_condition">race - conditions</a>. - </Principle> - - <Principle name="Bugs are not recoverable errors"> - We believe in the <a href="http://joeduffyblog.com/2016/02/07/the-error-model/">Midori Error - Model</a>; that is, there are two kinds of errors: <i>recoverable errors</i> and <i>program - bugs</i>. Recoverable errors are things like illegal user input, network errors, etc. Errors - that can be anticipated and where there is a chance of recovery. Program bugs, on the other - hand, are unanticipated and we cannot expect to recover from them. We should treat these two - types of errors differently: For recoverable errors, we should enforce that they are checked - and handled. For program bugs, we should terminate execution as quickly as possible to prevent - data corruption and security issues. - </Principle> - - <Principle name="Fail fast, fail hard"> - To aid debugging and prevent potential harmful behaviour, Flix aborts execution when an - unrecoverable error is encountered. - - In the presence of concurrency, if a process fails, Flix aborts the entire program. - This ensures that the outside environment is duly notified and can take corrective action, e.g. - to restart the program. - </Principle> - - <Principle name="No pre-processor"> - Flix does not have and will not have a pre-processor. Programs that use pre-processing for - textual code generation are notoriously difficult to understand and debug. We want to avoid - that for Flix. Instead, Flix may some day have a macro system, but so far there has been little - need. - </Principle> - - <Principle name="No null value"> - Flix does not have the <code>null</code> value. The null value is now widely considered a - mistake and languages such as C#, Dart, Kotlin and Scala are scrambling to adopt mechanisms to - ensure non-nullness. - In Flix, we adopt the standard solution from functional languages which is to represent - the absence of a value using the <code>Option</code> type. This solution is simple to - understand, works well, and guarantees the absence of dreaded <code>NullPointerException</code>s. - </Principle> - - <Principle name="No implicit coercions"> - In Flix, a value of one type is never implicitly coerced or converted into a value of another - type. For example, - - <ul> - <li>No value is ever coerced to a boolean.</li> - <li>No value is ever coerced to a string.</li> - <li>Integers and floating-point are never truncated or promoted.</li> - </ul> - </Principle> - - <Principle name="No reflection"> - Flix does not support reflection, i.e. the ability to inspect the structure of the program - at run-time. Reflection tends to break the kind of program reasoning that both compilers and - humans rely on. At some point in the future, Flix might support some notion of compile-time - meta programming. - </Principle> - - <Principle name="No warnings, only errors"> - The Flix compiler never emits warnings; only compile-time errors which abort compilation. - Warnings can be ignored or turned off. People disagree on whether a warning is harmless or not. - For Flix, we believe that any code that appears troublesome or incorrect to the compiler should - outright be rejected. - </Principle> - - <Principle name="No unused declarations"> - Inspired by <a href="https://doc.rust-lang.org/rust-by-example/attribute/unused.html">Rust</a>, - the Flix compiler will reject programs that contain unused declarations. We believe - that rejecting such programs will help programmers avoid mistakes where some algebraic data - type or function is unintentionally left unused. - </Principle> - - <Principle name="No unused variables"> - Flix disallows unused local variables, whether they are introduced by let, introduced by pattern - matching, or part of the formal parameters of a function. Research [<a - href="https://dl.acm.org/citation.cfm?id=587060">1</a>] [<a - href="https://dl.acm.org/citation.cfm?id=1052895">2</a>] has repeatedly shown that minor - mistakes are a common source of bugs, e.g. using the wrong local variable. Disallowing unused - local variables help avoid such mistakes. - </Principle> - - <Principle name="No variable shadowing"> - Flix disallows variable shadowing for the same reasons why it disallows unused local variables: - it is a persistent and common source of minor mistakes leading to bugs. - </Principle> - - <Principle name="No unprincipled overloading"> - Flix does not support function overloading (using the same name for different functions). - Instead, Flix encourages the use of meaningful names, - e.g. <code>Map.filter</code> and <code>Map.filterWithKey</code>, for functions that share - similar functionality. - </Principle> - - <Principle name="No variadic (varargs) functions"> - Flix does not support variadic (varargs) functions. It is not clear to us how a language design - can support both currying and variadic functions cleanly. Moreover, it seems that the supposed - benefits of variadic functions is not that great in a language which already has concise syntax - for list and array literals. - </Principle> - - <Principle name="No labelled function arguments"> - Flix does not support labelled function arguments. The motivation for labelled arguments is a - reasonable: to avoid calling a function with arguments of the same type, but in the wrong order. - Unfortunately, labelled function arguments do not work in the presence of higher-order - functions. Instead, we suggest to overcome the problem by either (i) using richer types - (e.g. <code>Celsius</code> instead of <code>Int</code>) or alternatively (ii) using record types - which can be used to emulate the same functionality and works with higher-order functions. - </Principle> - - <Principle name="No binary or octal literals"> - Flix does not support binary or octal literals. It is our understanding that these features are - rarely used in practice. - </Principle> - - <Principle name="Exhaustive pattern matches"> - The Flix compiler enforces that pattern matches handle all cases of an algebraic data type. - If a match expression is found to be non-exhaustive, the program is rejected. We believe this - encourages more robust code and enables safer refactoring of algebraic data types. - </Principle> - - <Principle name="Timeless design"> - A few years ago HTML was all the rage. Hence it was only natural that Java adopted HTML-style - comments. A bit later, XML was all the rage, hence it was only natural that Scala - added support for native XML literals. Today, JSON and Markdown are all the rage, but if - history is any guide, we should not add any special support for these to Flix. - </Principle> - - <Principle name="Built-in documentation"> - Flix supports comments as part of the language. We believe such integration avoids fragmentation - of the ecosystem and ultimately leads to better tool support. - </Principle> - - <Principle name="Built-in unit tests"> - Flix supports unit tests as part of the language. We believe such integration avoids - fragmentation of the ecosystem and ultimately leads to better tool support. - </Principle> - - </CardColumns> - - <h2 className="mt-3">Compiler Message Principles</h2> - - <p> - Compiler messages are the main interface between Flix and programmers. We should invest into it. - </p> - - <CardColumns> - <Principle name="The 80 / 20 Rule"> - <p> - The rule states that 80% of the time a developer will need minimal information to understand - a compiler message. Most likely the developer will already have seen the specific - error message hundreds of times before. But 20% of the time, the developer will - never have seen the message before and will need more information. - </p> - - <p> - Flix compiler messages should accommodate both scenarios. - </p> - </Principle> - - <Principle name="Message Structure"> - <p> - A compiler message consists of three components: - - <ul> - <li><b>Summary:</b> A one sentence summary. The message shown on hover in Visual Studio - Code. - </li> - <li><b>Message:</b> A multi-line text that contains all relevant details, including - the program symbol(s) and fragment(s) relevant for the message. - </li> - <li><b>Explanation:</b> A description of why the problem occurs and what can be done - to fix it. - </li> - </ul> - </p> - </Principle> - - <Principle name="Style and Tone"> - <p> - A message should be <b>crisp</b>, <b>concise</b>, and <b>clear</b>. - The language should be friendly or neutral. An error message should not blame - the programmer. For example, we should prefer <code>Unexpected foo</code> over <code>Illegal - foo</code>, since the latter implies that the programmer did something wrong. - </p> - </Principle> - - <Principle name="Straight to the Point"> - <p> - The error message: <code>Duplicate definition: 'foo'</code> is better than the error - message: <code>The definition 'foo' is defined twice</code> because in the former the - programmer only has to scan the first word to understand what is wrong. - </p> - </Principle> - - <Principle name="Compare to Other Languages"> - <p> - When relevant, a Flix compiler error should explain how Flix differs from other languages - and explain how the specific problem can be solved in Flix. - </p> - </Principle> - </CardColumns> - - <h2 className="mt-3">Type Class Principles</h2> - - <CardColumns> - <Principle name="Type Classes are Conceptually Functions"> - <p> - A type class is <i>conceptually</i> a function from a type to a set of lawful - operations (called signatures) on values of that type. - </p> - - <p> - For example, the <code>Eq</code> type class takes a type and returns - the <code>eq</code> and <code>neq</code> functions where <code>eq</code> must be reflexive, - symmetric, and transitive, and <code>neq</code> must be - the negation of <code>eq</code>. - </p> - </Principle> - - <Principle name="Lawful and Lawless Type Classes"> - <p> - Every type class must specify a collection of laws that instances of the type - class must satisfy. If a type class does not specify any laws it is lawless. - </p> - - <p> - Here are some examples of lawful and lawless type classes: - - <ul> - <li>Lawful: <code>Eq</code>, <code>Order</code>, <code>Functor</code>, <code>Foldable</code>. - </li> - <li>Lawless: <code>FromString</code>, <code>ToString</code>, <code>Add</code>.</li> - </ul> - </p> - - <p> - A type class is lawful if every signature of the class is used in at least one law. - </p> - - <p> - Note: Laws are not checked by the compiler – that is an undecidable - problem – but they may be used in a future SmallCheck / QuickCheck library. - </p> - - </Principle> - - <Principle name="Type Classes are Hierarchical"> - <p> - A sub-class (i.e. a type class <code>A</code> that refines a type class <code>B</code>) must - specify additional laws that its instances must satisfy. - </p> - - <p> - For example, the <code>Applicative</code> type class extends the <code>Functor</code> type - class with additional operations and laws. - </p> - </Principle> - - <Principle name="No Orphan Instances"> - An instance must be declared in the same namespace as either: - - <ol> - <li>the type class declaration, or</li> - <li>the type declaration of the instance</li> - </ol> - </Principle> - - <Principle name="Sealed Type Classes"> - A type class may be declared <code>sealed</code> in which case no further instances, other than - those in the same namespace, can be defined. A sealed type class can be used when the programmer - wants to maintain tight control over what instances should be permitted. - </Principle> - - <Principle name="No Overlapping Instances"> - <p> - The Flix compiler ensures that the selection of type class instances is always unambiguous. - </p> - - <p> - In the future, we may allow a limited form of overlapping instances. - </p> - </Principle> - - <Principle name="Type Classes, Namespaces, and Companion Namespaces"> - <p> - Every type class belongs to a namespace. Hence it is possible to define multiple operations - with the same name, as long as they belong to type classes in different namespaces. - </p> - - <p> - Every type class also defines a <i>companion namespace</i> which typically holds functions - that are not part of the type class, but nevertheless are related to the functionality of - the type class. - </p> - </Principle> - - <Principle name="Default Implementations"> - <p> - Type classes may provide default implementations of functions. - </p> - - <p> - For example, the <code>Foldable</code> type class may provide default function - implementations, e.g. <code>count</code> and <code>length</code>, based on - the <code>foldLeft</code> and <code>foldRight</code> signatures defined in that class. - </p> - - <p> - A default implementation can always be overriden by a specific type class instance. - For example, to provide a more efficient version. - </p> - </Principle> - - <Principle name="Explicit Override"> - A type class instance that wants to override a default implementation must explicitly do - so using the <code>override</code> keyword. This ensures that there are no dangling overrides, - i.e. functions definitions that do not match any signature of the type class. - </Principle> - - </CardColumns> - - <h2 className="mt-3">Library Principles</h2> - - <CardColumns> - - <Principle name="No blessed library"> - The Flix standard library is implemented in Flix. It has no special support from the compiler. - If you don't like it or if you don't need it, you can replace it. - </Principle> - - <Principle name="Minimal prelude"> - The Flix prelude contains algebraic data types and functions that are imported into every - compilation unit. Therefore we aim to keep the prelude very small and only include extremely - common functionality. - </Principle> - - <Principle name="Mutable data is functional data"> - In Flix, every mutable data structure supports functional operations. - For example, mutable collections, such as <code>Array</code> and <code>MutSet</code> support - the <code>map</code> operation. Flix, being functional-first, reserves functional names for - functional operations. Across the standard library <code>map</code> has the same name and the - same type signature. - </Principle> - - <Principle name="Destructive operations are marked with '!'"> - In Flix, every destructive operation is suffixed with an exclamation point. For - example, <code>Array.reverse(a)</code> returns a new array with the elements - of <code>a</code> in reverse - order, whereas <code>Array.reverse!(a)</code> destructively re-orders the elements - of <code>a</code>. Note: This principle applies to destructive operations that operate on data - structures, not to impure functions in general, e.g. <code>Console.printLine</code>. - </Principle> - - <Principle name="Consistent names of functional and destructive operations"> - In Flix, functional and destructive operations that share (i) similar behavior and (ii) similar - type signatures share similar names. For - example, <code>Array.reverse</code> and <code>Array.reverse!</code> share the - same name. On the other hand, <code>Array.transform!</code> is - called <code>transform!</code> and not <code>map!</code> because its type signature is - dissimilar to map (i.e. map works on functions of type <code>a -{'>'} b</code>, but transform - requires functions of type <code>a -{'>'} a</code>.) - </Principle> - - </CardColumns> - - </Container> - ); - } + componentDidMount() { + document.title = 'Flix | Principles' + } + + render() { + return ( + <Container> + <h1>Design Principles</h1> + + <p className="mb-3"> + We believe that the development of a programming language should follow a set of principles. That is, when a + design decision is made there should exist some rationale for why that decision was made. By outlining these + principles, as we develop Flix, we hope to keep ourselves honest and to communicate the kind of language Flix + aspires to be. + </p> + + <p className="mb-3"> + Many of these ideas and principles come from languages that have inspired Flix, including Ada, Elm, F#, Go, + Haskell, OCaml, Rust, and Scala. + </p> + + <p> + <b>Update:</b> The Flix Principles has been published in a paper at Onward! '22. Read it here:{' '} + <a href="https://dl.acm.org/doi/10.1145/3563835.3567661">The Principles of the Flix Programming Language</a>. + </p> + + <h2 className="mt-3">Language Principles</h2> + + <CardColumns> + <Principle name="Simple is not easy"> + We believe in Rich Hickey's creed:{' '} + <a href="https://www.infoq.com/presentations/Simple-Made-Easy">simple is not easy</a>. We prefer a language + that gets things right to one that makes things easy. Such a language might take longer to learn in the + short run, but its simplicity pays off in the long run. + </Principle> + + <Principle name="Everything is an expression"> + Flix is a functional language and embraces the idea that everything should be an expression. Flix has no + local variable declarations or if-then-else statements, instead it has let-bindings and if-then-else + expressions. However, Flix does not take this idea as far as the Scheme languages. Flix still has + declarations, namespaces, and so forth that are not expressions. + </Principle> + + <Principle name="Separate pure and impure code"> + Flix supports functional, imperative, and logic programming. The type and effect system of Flix cleanly and + safely separates pure code from impure code. That is, if a function is pure then the programmer can trust + that the function behaves like a mathematical function: it returns the same value when given the same + arguments and it has no side-effects. + </Principle> + + <Principle name="Developer productivity over runtime performance"> + Flix aims to support developer productivity; the ability to do a lot with little ceremony or boilerplate. A + hand-crafted C program might run faster than a Flix program, but it won't be as short, concise, or + expressive as the Flix program. Flix aims to be a language with powerful constructs and high-level + abstractions. This does not mean that Flix is slow. + </Principle> + + <Principle name="Correctness over performance"> + Flix aims to ensure program correctness and considers it more important than raw performance. Languages such + as C and C++ often rely on undefined behaviour to achieve stellar performance, whereas most other languages, + including Flix, try to eschew undefined behaviour in favor of runtime checks for things that are hard to + statically ensure. For example, most languages will dynamically check that array accesses are not out of + bounds. The cost is a small performance hit, but in our view the benefit towards correctness is immense. + Inspired by Ada, Flix aims to offer strong guarantees, ideally ensured statically, but when necessary with + dynamic checks. + </Principle> + + <Principle name="One language"> + Flix is <i>one</i> programming language. The Flix compiler does not have feature flags or compiler plugins + that change or extend the semantics of the language. We want to avoid fragmentation in the ecosystem where + programs end up being written in different "dialects" of the language. There is one language, now and + forever. Of course that does not imply that the language will not evolve over time. + </Principle> + + <Principle name="Principle of least surprise"> + We should strive to adhere to the{' '} + <a href="https://en.wikipedia.org/wiki/Principle_of_least_astonishment">principle of least surprise</a>. + That is, we should favor sane defaults, and when there is no immediately obvious default, we should not have + a default at all, but force the programmer to be explicit about his or her intention. + </Principle> + + <Principle name="Local type inference"> + The Flix type system is based on{' '} + <a href="https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system">Hindley-Milner</a> which supports + full type inference. As a design choice, we require all functions to be annotated with their argument and + return types. We believe that requiring type signatures has three distinct advantages that outweigh the + disadvantages. + <ol> + <li>Type signatures are useful as documentation and to aid program understanding.</li> + <li>Type signatures accurately assign blame for type errors.</li> + <li>Type signatures enable parallel type checking.</li> + </ol> + Of these, we think the former two are significantly more important than the latter. + </Principle> + + <Principle name="Type parameter elision"> + While we require type signatures, we also believe that such signatures should be as minimal as possible. + Thus, while the full type signature of <code>List.map</code> is{' '} + <code>def map[a, b](f: a -{'>'} b, xs: List[a]): List[b]</code>, we can use <i>type parameter elision</i> to + write it simply as: <code>def map(f: a -{'>'} b, xs: List[a]): List[b]</code> omitting the type arguments. + </Principle> + + <Principle name="Syntax vs. Semantics"> + Syntax is important. Semantics are important. But we should not confuse the two. A syntactic issue should + not be resolved by a enrichment of the semantics. For example,{' '} + <a href=" https://en.wikipedia.org/wiki/Extension_method">extension methods</a> and{' '} + <a href="https://docs.scala-lang.org/overviews/core/implicit-classes.html">implicit classes</a> seem to be + semantic solutions to (mostly) syntactic issues. Flix aims to avoid such pitfalls. + </Principle> + + <Principle name="Keyword-based syntax"> + The Flix syntax is inspired by Scala. We believe that short key words make it easy to visually identify the + overall structure of a piece of code. Flix tries to use three letter keywords where appropriate:{' '} + <code>def</code>, <code>let</code>, <code>law</code>,<code>rel</code>, but not for commonly established + concepts: <code>if ... else </code> + and <code>match</code>. + </Principle> + + <Principle name="Consistent syntax"> + Flix aims to have consistent and predictable syntax. As an example, we try to have the syntax of types + mirror that of expressions: + <ul> + <li> + A function application is written as <code>f(a, b, c)</code> whereas a type application is written as{' '} + <code>f[a, b, c]</code>. + </li> + <li> + A function expression is written as <code>x -> x + 1</code> whereas a function type is written as{' '} + <code>Int -> Int</code>. + </li> + <li> + A tuple is written as <code>(true, 12345)</code> whereas a tuple type is written as{' '} + <code>(Bool, Int)</code>. + </li> + </ul> + </Principle> + + <Principle name="Human-readable errors"> + In the spirit of <a href="https://elm-lang.org/blog/compilers-as-assistants">Elm</a> and{' '} + <a href="https://blog.rust-lang.org/2016/08/10/Shape-of-errors-to-come.html">Rust</a>, Flix aims to have + human readable and understandable compiler messages. Messages should describe the problem in detail and + provide information about the context, including suggestions for how to correct the problem. + </Principle> + + <Principle name="Private by default"> + Flix embraces the principle of least privilege. In Flix, declarations are hidden by default (i.e. private) + and cannot be accessed from outside of their namespace (or sub-namespaces). We believe it is important that + programmers are forced to make a conscious choice about when to make a declaration publicly visible. + </Principle> + + <Principle name="Closed world assumption"> + Flix requires all code to be available at compile-time. This enables a range of compilation techniques, such + as: + <ul> + <li>Monomorphization to avoid unnecessary boxing of primitives.</li> + <li>Aggressive dead code elimination ("tree shaking") to remove unused functions.</li> + <li>Inlining across namespaces.</li> + <li>Whole-program analysis.</li> + </ul> + </Principle> + + <Principle name="Illegal states should be unrepresentable"> + We believe that a language should make it easy to make illegal states unrepresentable. For example, + algebraic data types can be used to precisely define the possible values of a type. In Flix, in the future, + we want to take this a step further, and allow refinement of some types. For example, to express that some + value must not only be an integer, but also that it must fall within a range, e.g. <code>[0-99]</code>. + <br /> + <Badge>in progress</Badge> + </Principle> + + <Principle name="Nothing is executed before main"> + In Flix, <code>main</code> is the entry point of a program. No (user-defined) code is ever executed before{' '} + <code>main</code>. No static initializers, no static fields. No class loaders. Main is always first. This + makes it easy to reason about startup behavior. + </Principle> + + <Principle name="Small, but comprehensive standard library"> + Flix has a small standard library with a few common data types, e.g. <code>Option</code>, <code>List</code>,{' '} + <code>Set</code>, and <code>Map</code>, but for these it offers a comprehensive collection of functionality. + For example, the standard library has more than 65 functions for working with lists. We want the standard + library to offer a common set of abstractions which are usable by most programs, but not much else. + </Principle> + + <Principle name="Declare before use"> + In Flix things must be defined before they can be used. Algebraic data types, functions, local variables, + and other programming elements must be declared before they can be used by other program parts. Declarations + make it easy to assign blame; we assume declarations to be correct and check every use against its + declaration. For example, an algebraic data type declares a set of cases, and the compiler checks that every + use refers to one of these cases, and that every case is covered. + </Principle> + + <Principle name="No unnecessary declarations"> + We believe that a programming language should reduce the volume of declarations it <i>requires</i>. + Declarations may be useful and are sometimes necessary, but Flix aims to minimize its internal dependence on + them. To give an example, Flix supports <i>extensible records</i> which permits the usage of flexible and + type-safe records <i>without</i> a strict requirement that record types must be declared upfront. + </Principle> + + <Principle name="No global state"> + In Flix there is no global shared state. This avoids a plethora of issues, including difficulties with + initialization order and race conditions in the presence of concurrency. A Flix programmer is free to + construct some state in the main function and pass it around, but there is no built-in mechanism to declare + global variables. In a real system, the programmer still has to deal with the state of the world, e.g. the + state of the file system, the network, and other resources. + </Principle> + + <Principle name="Share memory by communicating"> + Flix follows the Go mantra:{' '} + <a href="https://blog.golang.org/share-memory-by-communicating"> + <i>Do not communicate by sharing memory; instead, share memory by communicating.</i> + </a>{' '} + In other words: mutable memory should never be shared between processes. Processes should only share + immutable messages (and data structures). We believe this significantly reduces the risk of{' '} + <a href="https://en.wikipedia.org/wiki/Race_condition">race conditions</a>. + </Principle> + + <Principle name="Bugs are not recoverable errors"> + We believe in the <a href="http://joeduffyblog.com/2016/02/07/the-error-model/">Midori Error Model</a>; that + is, there are two kinds of errors: <i>recoverable errors</i> and <i>program bugs</i>. Recoverable errors are + things like illegal user input, network errors, etc. Errors that can be anticipated and where there is a + chance of recovery. Program bugs, on the other hand, are unanticipated and we cannot expect to recover from + them. We should treat these two types of errors differently: For recoverable errors, we should enforce that + they are checked and handled. For program bugs, we should terminate execution as quickly as possible to + prevent data corruption and security issues. + </Principle> + + <Principle name="Fail fast, fail hard"> + To aid debugging and prevent potential harmful behaviour, Flix aborts execution when an unrecoverable error + is encountered. In the presence of concurrency, if a process fails, Flix aborts the entire program. This + ensures that the outside environment is duly notified and can take corrective action, e.g. to restart the + program. + </Principle> + + <Principle name="No pre-processor"> + Flix does not have and will not have a pre-processor. Programs that use pre-processing for textual code + generation are notoriously difficult to understand and debug. We want to avoid that for Flix. Instead, Flix + may some day have a macro system, but so far there has been little need. + </Principle> + + <Principle name="No null value"> + Flix does not have the <code>null</code> value. The null value is now widely considered a mistake and + languages such as C#, Dart, Kotlin and Scala are scrambling to adopt mechanisms to ensure non-nullness. In + Flix, we adopt the standard solution from functional languages which is to represent the absence of a value + using the <code>Option</code> type. This solution is simple to understand, works well, and guarantees the + absence of dreaded <code>NullPointerException</code>s. + </Principle> + + <Principle name="No implicit coercions"> + In Flix, a value of one type is never implicitly coerced or converted into a value of another type. For + example, + <ul> + <li>No value is ever coerced to a boolean.</li> + <li>No value is ever coerced to a string.</li> + <li>Integers and floating-point are never truncated or promoted.</li> + </ul> + </Principle> + + <Principle name="No reflection"> + Flix does not support reflection, i.e. the ability to inspect the structure of the program at run-time. + Reflection tends to break the kind of program reasoning that both compilers and humans rely on. At some + point in the future, Flix might support some notion of compile-time meta programming. + </Principle> + + <Principle name="No warnings, only errors"> + The Flix compiler never emits warnings; only compile-time errors which abort compilation. Warnings can be + ignored or turned off. People disagree on whether a warning is harmless or not. For Flix, we believe that + any code that appears troublesome or incorrect to the compiler should outright be rejected. + </Principle> + + <Principle name="No unused declarations"> + Inspired by <a href="https://doc.rust-lang.org/rust-by-example/attribute/unused.html">Rust</a>, the Flix + compiler will reject programs that contain unused declarations. We believe that rejecting such programs will + help programmers avoid mistakes where some algebraic data type or function is unintentionally left unused. + </Principle> + + <Principle name="No unused variables"> + Flix disallows unused local variables, whether they are introduced by let, introduced by pattern matching, + or part of the formal parameters of a function. Research [ + <a href="https://dl.acm.org/citation.cfm?id=587060">1</a>] [ + <a href="https://dl.acm.org/citation.cfm?id=1052895">2</a>] has repeatedly shown that minor mistakes are a + common source of bugs, e.g. using the wrong local variable. Disallowing unused local variables help avoid + such mistakes. + </Principle> + + <Principle name="No variable shadowing"> + Flix disallows variable shadowing for the same reasons why it disallows unused local variables: it is a + persistent and common source of minor mistakes leading to bugs. + </Principle> + + <Principle name="No unprincipled overloading"> + Flix does not support function overloading (using the same name for different functions). Instead, Flix + encourages the use of meaningful names, e.g. <code>Map.filter</code> and <code>Map.filterWithKey</code>, for + functions that share similar functionality. + </Principle> + + <Principle name="No variadic (varargs) functions"> + Flix does not support variadic (varargs) functions. It is not clear to us how a language design can support + both currying and variadic functions cleanly. Moreover, it seems that the supposed benefits of variadic + functions is not that great in a language which already has concise syntax for list and array literals. + </Principle> + + <Principle name="No labelled function arguments"> + Flix does not support labelled function arguments. The motivation for labelled arguments is a reasonable: to + avoid calling a function with arguments of the same type, but in the wrong order. Unfortunately, labelled + function arguments do not work in the presence of higher-order functions. Instead, we suggest to overcome + the problem by either (i) using richer types (e.g. <code>Celsius</code> instead of <code>Int</code>) or + alternatively (ii) using record types which can be used to emulate the same functionality and works with + higher-order functions. + </Principle> + + <Principle name="No binary or octal literals"> + Flix does not support binary or octal literals. It is our understanding that these features are rarely used + in practice. + </Principle> + + <Principle name="Exhaustive pattern matches"> + The Flix compiler enforces that pattern matches handle all cases of an algebraic data type. If a match + expression is found to be non-exhaustive, the program is rejected. We believe this encourages more robust + code and enables safer refactoring of algebraic data types. + </Principle> + + <Principle name="Timeless design"> + A few years ago HTML was all the rage. Hence it was only natural that Java adopted HTML-style comments. A + bit later, XML was all the rage, hence it was only natural that Scala added support for native XML literals. + Today, JSON and Markdown are all the rage, but if history is any guide, we should not add any special + support for these to Flix. + </Principle> + + <Principle name="Built-in documentation"> + Flix supports comments as part of the language. We believe such integration avoids fragmentation of the + ecosystem and ultimately leads to better tool support. + </Principle> + + <Principle name="Built-in unit tests"> + Flix supports unit tests as part of the language. We believe such integration avoids fragmentation of the + ecosystem and ultimately leads to better tool support. + </Principle> + </CardColumns> + + <h2 className="mt-3">Compiler Message Principles</h2> + + <p>Compiler messages are the main interface between Flix and programmers. We should invest into it.</p> + + <CardColumns> + <Principle name="The 80 / 20 Rule"> + <p> + The rule states that 80% of the time a developer will need minimal information to understand a compiler + message. Most likely the developer will already have seen the specific error message hundreds of times + before. But 20% of the time, the developer will never have seen the message before and will need more + information. + </p> + + <p>Flix compiler messages should accommodate both scenarios.</p> + </Principle> + + <Principle name="Message Structure"> + <p> + A compiler message consists of three components: + <ul> + <li> + <b>Summary:</b> A one sentence summary. The message shown on hover in Visual Studio Code. + </li> + <li> + <b>Message:</b> A multi-line text that contains all relevant details, including the program symbol(s) + and fragment(s) relevant for the message. + </li> + <li> + <b>Explanation:</b> A description of why the problem occurs and what can be done to fix it. + </li> + </ul> + </p> + </Principle> + + <Principle name="Style and Tone"> + <p> + A message should be <b>crisp</b>, <b>concise</b>, and <b>clear</b>. The language should be friendly or + neutral. An error message should not blame the programmer. For example, we should prefer{' '} + <code>Unexpected foo</code> over <code>Illegal foo</code>, since the latter implies that the programmer + did something wrong. + </p> + </Principle> + + <Principle name="Straight to the Point"> + <p> + The error message: <code>Duplicate definition: 'foo'</code> is better than the error message:{' '} + <code>The definition 'foo' is defined twice</code> because in the former the programmer only has to scan + the first word to understand what is wrong. + </p> + </Principle> + + <Principle name="Compare to Other Languages"> + <p> + When relevant, a Flix compiler error should explain how Flix differs from other languages and explain how + the specific problem can be solved in Flix. + </p> + </Principle> + </CardColumns> + + <h2 className="mt-3">Type Class Principles</h2> + + <CardColumns> + <Principle name="Type Classes are Conceptually Functions"> + <p> + A type class is <i>conceptually</i> a function from a type to a set of lawful operations (called + signatures) on values of that type. + </p> + + <p> + For example, the <code>Eq</code> type class takes a type and returns the <code>eq</code> and{' '} + <code>neq</code> functions where <code>eq</code> must be reflexive, symmetric, and transitive, and{' '} + <code>neq</code> must be the negation of <code>eq</code>. + </p> + </Principle> + + <Principle name="Lawful and Lawless Type Classes"> + <p> + Every type class must specify a collection of laws that instances of the type class must satisfy. If a + type class does not specify any laws it is lawless. + </p> + + <p> + Here are some examples of lawful and lawless type classes: + <ul> + <li> + Lawful: <code>Eq</code>, <code>Order</code>, <code>Functor</code>, <code>Foldable</code>. + </li> + <li> + Lawless: <code>FromString</code>, <code>ToString</code>, <code>Add</code>. + </li> + </ul> + </p> + + <p>A type class is lawful if every signature of the class is used in at least one law.</p> + + <p> + Note: Laws are not checked by the compiler – that is an undecidable problem – but they may be + used in a future SmallCheck / QuickCheck library. + </p> + </Principle> + + <Principle name="Type Classes are Hierarchical"> + <p> + A sub-class (i.e. a type class <code>A</code> that refines a type class <code>B</code>) must specify + additional laws that its instances must satisfy. + </p> + + <p> + For example, the <code>Applicative</code> type class extends the <code>Functor</code> type class with + additional operations and laws. + </p> + </Principle> + + <Principle name="No Orphan Instances"> + An instance must be declared in the same namespace as either: + <ol> + <li>the type class declaration, or</li> + <li>the type declaration of the instance</li> + </ol> + </Principle> + + <Principle name="Sealed Type Classes"> + A type class may be declared <code>sealed</code> in which case no further instances, other than those in the + same namespace, can be defined. A sealed type class can be used when the programmer wants to maintain tight + control over what instances should be permitted. + </Principle> + + <Principle name="No Overlapping Instances"> + <p>The Flix compiler ensures that the selection of type class instances is always unambiguous.</p> + + <p>In the future, we may allow a limited form of overlapping instances.</p> + </Principle> + + <Principle name="Type Classes, Namespaces, and Companion Namespaces"> + <p> + Every type class belongs to a namespace. Hence it is possible to define multiple operations with the same + name, as long as they belong to type classes in different namespaces. + </p> + + <p> + Every type class also defines a <i>companion namespace</i> which typically holds functions that are not + part of the type class, but nevertheless are related to the functionality of the type class. + </p> + </Principle> + + <Principle name="Default Implementations"> + <p>Type classes may provide default implementations of functions.</p> + + <p> + For example, the <code>Foldable</code> type class may provide default function implementations, e.g.{' '} + <code>count</code> and <code>length</code>, based on the <code>foldLeft</code> and <code>foldRight</code>{' '} + signatures defined in that class. + </p> + + <p> + A default implementation can always be overriden by a specific type class instance. For example, to + provide a more efficient version. + </p> + </Principle> + + <Principle name="Explicit Override"> + A type class instance that wants to override a default implementation must explicitly do so using the{' '} + <code>override</code> keyword. This ensures that there are no dangling overrides, i.e. functions definitions + that do not match any signature of the type class. + </Principle> + </CardColumns> + + <h2 className="mt-3">Library Principles</h2> + + <CardColumns> + <Principle name="No blessed library"> + The Flix standard library is implemented in Flix. It has no special support from the compiler. If you don't + like it or if you don't need it, you can replace it. + </Principle> + + <Principle name="Minimal prelude"> + The Flix prelude contains algebraic data types and functions that are imported into every compilation unit. + Therefore we aim to keep the prelude very small and only include extremely common functionality. + </Principle> + + <Principle name="Mutable data is functional data"> + In Flix, every mutable data structure supports functional operations. For example, mutable collections, such + as <code>Array</code> and <code>MutSet</code> support the <code>map</code> operation. Flix, being + functional-first, reserves functional names for functional operations. Across the standard library{' '} + <code>map</code> has the same name and the same type signature. + </Principle> + + <Principle name="Destructive operations are marked with '!'"> + In Flix, every destructive operation is suffixed with an exclamation point. For example,{' '} + <code>Array.reverse(a)</code> returns a new array with the elements of <code>a</code> in reverse order, + whereas <code>Array.reverse!(a)</code> destructively re-orders the elements of <code>a</code>. Note: This + principle applies to destructive operations that operate on data structures, not to impure functions in + general, e.g. <code>Console.printLine</code>. + </Principle> + + <Principle name="Consistent names of functional and destructive operations"> + In Flix, functional and destructive operations that share (i) similar behavior and (ii) similar type + signatures share similar names. For example, <code>Array.reverse</code> and <code>Array.reverse!</code>{' '} + share the same name. On the other hand, <code>Array.transform!</code> is called <code>transform!</code> and + not <code>map!</code> because its type signature is dissimilar to map (i.e. map works on functions of type{' '} + <code>a -{'>'} b</code>, but transform requires functions of type <code>a -{'>'} a</code>.) + </Principle> + </CardColumns> + </Container> + ) + } } class Principle extends Component { - render() { - return ( - <Card> - <CardBody> - <CardTitle>{this.props.name}</CardTitle> - {this.props.children} - </CardBody> - </Card> - ); - } + render() { + return ( + <Card> + <CardBody> + <CardTitle>{this.props.name}</CardTitle> + {this.props.children} + </CardBody> + </Card> + ) + } } -export default Principles; +export default Principles diff --git a/src/page/Research.js b/src/page/Research.js index 14b2c33..03bba1a 100644 --- a/src/page/Research.js +++ b/src/page/Research.js @@ -1,159 +1,166 @@ -import React, {Component} from 'react'; -import {Container} from "reactstrap"; +import React, { Component } from 'react' +import { Container } from 'reactstrap' class Research extends Component { - - componentDidMount() { - document.title = "Flix | Research"; - } - - render() { - return ( - <Container> - <h1>Research</h1> - - <p> - Research on Flix takes place at <a href="http://cs.au.dk/research/programming-languages/">Aarhus - University</a> and the <a - href="http://plg.uwaterloo.ca">University of Waterloo</a>. - </p> - - <p> - Below is a selection of research papers published on Flix: - </p> - - <h3>Talks</h3> - - <ul> - <li> - <a href="/talks/dahl-nygaard.pdf"> - An Introduction to the Flix Programming Language - </a> <b>[Dahl-Nygaard Prize, ECOOP '22]</b> - </li> - </ul> - - <h3>Peer-Reviewed</h3> - - <ul> - <Paper - title="The Principles of the Flix Programming Language" - authors="Magnus Madsen" - venue="Onward! '22" - url="/paper/onward2022.pdf"/> - - <Paper - title="Flix: A Meta Programming Language for Datalog" - authors="Magnus Madsen, Jonathan Lindegaard Starup, Ondřej Lhoták" - venue="Datalog '22" - url="/paper/datalog2022.pdf"/> - - <Paper - title="Relational Nullable Types with Boolean Unification" - authors="Magnus Madsen, Jaco van de Pol" - venue="OOPSLA '21" - url="/paper/oopsla2021.pdf"/> - - <Paper - title="Fixpoints for the Masses: Programming with First-Class Datalog Constraints" - authors="Magnus Madsen, Ondřej Lhoták" - venue="OOPSLA '20" - url="/paper/oopsla2020a.pdf"/> - - <Paper - title="Polymorphic Types and Effects with Boolean Unification" - authors="Magnus Madsen, Jaco van de Pol" - venue="OOPSLA '20" - url="/paper/oopsla2020b.pdf"/> - - <Paper - title="Implicit Parameters for Logic Programming" - authors="Magnus Madsen, Ondřej Lhoták" - venue="PPDP '18" - url="/paper/ppdp2018.pdf"/> - - <Paper - title="Safe and Sound Program Analysis with Flix" - authors="Magnus Madsen, Ondřej Lhoták" - venue="ISSTA '18" - url="/paper/issta2018.pdf"/> - - <Paper - title="Tail Call Elimination and Data Representation for Functional Languages on the Java Virtual Machine" - authors="Magnus Madsen, Ramin Zarifi, Ondřej Lhoták" - venue="CC '18" - url="/paper/cc2018.pdf"/> - - <Paper - title="From Datalog to Flix: A Declarative Language for Fixed Points on Lattices" - authors="Magnus Madsen, Ming-Ho Yee, Ondřej Lhoták" - venue="PLDI '16" - url="/paper/pldi2016.pdf"/> - </ul> - - <h3>Workshops</h3> - - <ul> - <Paper - title="Programming a Dataflow Analysis in Flix" - authors="Magnus Madsen, Ming-Ho Yee, Ondřej Lhoták" - venue="TAPAS '16" - url="http://staticanalysis.org/tapas2016/abstracts/TAPAS_2016_MadsenEtAl.pdf"/> - </ul> - - <h3>Theses</h3> - - <ul> - <Paper - title="Implementing a Functional Language for Flix" - authors="Ming-Ho Yee" - venue="University of Waterloo" - url="https://uwspace.uwaterloo.ca/bitstream/handle/10012/10856/Yee_Ming-Ho.pdf?sequence=1" - /> - </ul> - - <h3>Media</h3> - - <ul> - <li> - <b>InfoQ:</b> <a - href="https://www.infoq.com/news/2022/02/flix-programming-language/"> - Interview with Magnus Madsen about the Flix Programming Language - </a> - </li> - <li> - <b>Happy Path Programming:</b> <a - href="https://anchor.fm/happypathprogramming/episodes/54-Flix-Designing-a-principled-programming-language-with-Magnus-Madsen-e1dueb2"> - Episode 54: Flix: Designing a principled programming language with Magnus Madsen - </a> - </li> - <li> - <b>Version2:</b> <a - href="https://www.version2.dk/artikel/flix-nyt-sprog-aarhus-vil-goere-programmoerens-liv-lettere-med-logik-tanken-1093103"> - Flix: Nyt sprog fra Aarhus vil gøre programmørens liv lettere med logik i - tanken</a> – <i>Tania Andersen</i>. - </li> - <li> - <b>ComputerWorld:</b> <a - href="https://www.computerworld.dk/art/257120/datalogi-adjunkt-magnus-madsen-har-opfundet-et-nyt-programmeringssprog-vi-staar-over-for-et-skifte-inden-for-programmeringssprog-her-er-ideen-med-det-nye-flix"> - Datalogi-adjunkt Magnus Madsen har opfundet et nyt programmeringssprog: Vi står over for et - skifte inden for programmeringssprog - her er ideen med det nye Flix - </a> – <i>Jakob Schjoldager</i>. - </li> - </ul> - - </Container> - ); - } + componentDidMount() { + document.title = 'Flix | Research' + } + + render() { + return ( + <Container> + <h1>Research</h1> + + <p> + Research on Flix takes place at{' '} + <a href="http://cs.au.dk/research/programming-languages/">Aarhus University</a> and the{' '} + <a href="http://plg.uwaterloo.ca">University of Waterloo</a>. + </p> + + <p>Below is a selection of research papers published on Flix:</p> + + <h3>Talks</h3> + + <ul> + <li> + <a href="/talks/dahl-nygaard.pdf">An Introduction to the Flix Programming Language</a>{' '} + <b>[Dahl-Nygaard Prize, ECOOP '22]</b> + </li> + </ul> + + <h3>Peer-Reviewed</h3> + + <ul> + <Paper + title="The Principles of the Flix Programming Language" + authors="Magnus Madsen" + venue="Onward! '22" + url="/paper/onward2022.pdf" + /> + + <Paper + title="Flix: A Meta Programming Language for Datalog" + authors="Magnus Madsen, Jonathan Lindegaard Starup, Ondřej Lhoták" + venue="Datalog '22" + url="/paper/datalog2022.pdf" + /> + + <Paper + title="Relational Nullable Types with Boolean Unification" + authors="Magnus Madsen, Jaco van de Pol" + venue="OOPSLA '21" + url="/paper/oopsla2021.pdf" + /> + + <Paper + title="Fixpoints for the Masses: Programming with First-Class Datalog Constraints" + authors="Magnus Madsen, Ondřej Lhoták" + venue="OOPSLA '20" + url="/paper/oopsla2020a.pdf" + /> + + <Paper + title="Polymorphic Types and Effects with Boolean Unification" + authors="Magnus Madsen, Jaco van de Pol" + venue="OOPSLA '20" + url="/paper/oopsla2020b.pdf" + /> + + <Paper + title="Implicit Parameters for Logic Programming" + authors="Magnus Madsen, Ondřej Lhoták" + venue="PPDP '18" + url="/paper/ppdp2018.pdf" + /> + + <Paper + title="Safe and Sound Program Analysis with Flix" + authors="Magnus Madsen, Ondřej Lhoták" + venue="ISSTA '18" + url="/paper/issta2018.pdf" + /> + + <Paper + title="Tail Call Elimination and Data Representation for Functional Languages on the Java Virtual Machine" + authors="Magnus Madsen, Ramin Zarifi, Ondřej Lhoták" + venue="CC '18" + url="/paper/cc2018.pdf" + /> + + <Paper + title="From Datalog to Flix: A Declarative Language for Fixed Points on Lattices" + authors="Magnus Madsen, Ming-Ho Yee, Ondřej Lhoták" + venue="PLDI '16" + url="/paper/pldi2016.pdf" + /> + </ul> + + <h3>Workshops</h3> + + <ul> + <Paper + title="Programming a Dataflow Analysis in Flix" + authors="Magnus Madsen, Ming-Ho Yee, Ondřej Lhoták" + venue="TAPAS '16" + url="http://staticanalysis.org/tapas2016/abstracts/TAPAS_2016_MadsenEtAl.pdf" + /> + </ul> + + <h3>Theses</h3> + + <ul> + <Paper + title="Implementing a Functional Language for Flix" + authors="Ming-Ho Yee" + venue="University of Waterloo" + url="https://uwspace.uwaterloo.ca/bitstream/handle/10012/10856/Yee_Ming-Ho.pdf?sequence=1" + /> + </ul> + + <h3>Media</h3> + + <ul> + <li> + <b>InfoQ:</b>{' '} + <a href="https://www.infoq.com/news/2022/02/flix-programming-language/"> + Interview with Magnus Madsen about the Flix Programming Language + </a> + </li> + <li> + <b>Happy Path Programming:</b>{' '} + <a href="https://anchor.fm/happypathprogramming/episodes/54-Flix-Designing-a-principled-programming-language-with-Magnus-Madsen-e1dueb2"> + Episode 54: Flix: Designing a principled programming language with Magnus Madsen + </a> + </li> + <li> + <b>Version2:</b>{' '} + <a href="https://www.version2.dk/artikel/flix-nyt-sprog-aarhus-vil-goere-programmoerens-liv-lettere-med-logik-tanken-1093103"> + Flix: Nyt sprog fra Aarhus vil gøre programmørens liv lettere med logik i tanken + </a>{' '} + – <i>Tania Andersen</i>. + </li> + <li> + <b>ComputerWorld:</b>{' '} + <a href="https://www.computerworld.dk/art/257120/datalogi-adjunkt-magnus-madsen-har-opfundet-et-nyt-programmeringssprog-vi-staar-over-for-et-skifte-inden-for-programmeringssprog-her-er-ideen-med-det-nye-flix"> + Datalogi-adjunkt Magnus Madsen har opfundet et nyt programmeringssprog: Vi står over for et skifte inden + for programmeringssprog - her er ideen med det nye Flix + </a>{' '} + – <i>Jakob Schjoldager</i>. + </li> + </ul> + </Container> + ) + } } class Paper extends Component { - render() { - return ( - <li className="mb-1"> - <a href={this.props.url}>{this.props.title}</a> <b>[{this.props.venue}]</b> - </li> - ); - } + render() { + return ( + <li className="mb-1"> + <a href={this.props.url}>{this.props.title}</a> <b>[{this.props.venue}]</b> + </li> + ) + } } -export default Research; +export default Research diff --git a/src/page/blog/DesignFlaws.js b/src/page/blog/DesignFlaws.js index cbba24f..20c40f5 100644 --- a/src/page/blog/DesignFlaws.js +++ b/src/page/blog/DesignFlaws.js @@ -1,318 +1,281 @@ -import React, {Component} from "react"; -import {Col, Container, Row} from "reactstrap"; -import InlineEditor from "../../util/InlineEditor"; +import React, { Component } from 'react' +import { Col, Container, Row } from 'reactstrap' +import InlineEditor from '../../util/InlineEditor' class DesignFlaws extends Component { - - componentDidMount() { - document.title = "Flix | Design Flaws in Flix"; - } - - render() { - return ( - <Container style={{"text-align": "justify"}}> - <Row className="mb-3"> - <Col sm={12} md={8}> - - <h1>Design Flaws in Flix</h1> - - <p> - Posted January 2020 by <i>Magnus Madsen</i>. - </p> - - <p> - Inspired by the blog post <a - href="https://futhark-lang.org/blog/2019-12-18-design-flaws-in-futhark.html">Design Flaws in - Futhark</a>, I decided to take stock and reflect on some of the design flaws that I believe - we made during the development of the Flix programming language. I went through old - Github issues and pull requests to discover some of the challenging issues that we have been - or still are struggling with. I will classify the design flaws into four categories: - (i) design flaws that still plague the Flix language, (ii) design flaws that have been - fixed, (iii) poor designs that were thankfully never implemented, and finally (iv) design - choices where the jury is still out. - </p> - - <p> - I want to emphasize that language design and implementation is a herculean task and that - there are features planned for Flix which have not yet been implemented. The lack of a - specific feature is not a design flaw, but rather a question of when we can get around to - it. - </p> - - <h2>Design Flaws Present in Flix</h2> - - <p> - The following design flaws are still present in Flix. Hopefully some day they will be fixed. - </p> - - <h5>The Switch Expression</h5> - - <p> - Flix supports the <code>switch</code> expression: - </p> - - <InlineEditor> - {`switch { + componentDidMount() { + document.title = 'Flix | Design Flaws in Flix' + } + + render() { + return ( + <Container style={{ 'text-align': 'justify' }}> + <Row className="mb-3"> + <Col sm={12} md={8}> + <h1>Design Flaws in Flix</h1> + + <p> + Posted January 2020 by <i>Magnus Madsen</i>. + </p> + + <p> + Inspired by the blog post{' '} + <a href="https://futhark-lang.org/blog/2019-12-18-design-flaws-in-futhark.html"> + Design Flaws in Futhark + </a> + , I decided to take stock and reflect on some of the design flaws that I believe we made during the + development of the Flix programming language. I went through old Github issues and pull requests to + discover some of the challenging issues that we have been or still are struggling with. I will classify + the design flaws into four categories: (i) design flaws that still plague the Flix language, (ii) design + flaws that have been fixed, (iii) poor designs that were thankfully never implemented, and finally (iv) + design choices where the jury is still out. + </p> + + <p> + I want to emphasize that language design and implementation is a herculean task and that there are + features planned for Flix which have not yet been implemented. The lack of a specific feature is not a + design flaw, but rather a question of when we can get around to it. + </p> + + <h2>Design Flaws Present in Flix</h2> + + <p>The following design flaws are still present in Flix. Hopefully some day they will be fixed.</p> + + <h5>The Switch Expression</h5> + + <p> + Flix supports the <code>switch</code> expression: + </p> + + <InlineEditor> + {`switch { case cond1 => exp1 case cond2 => exp2 case cond3 => exp3 }`} - </InlineEditor> - - <p> - where the boolean expressions <code>cond1</code>, <code>cond2</code>, - and <code>cond3</code> are evaluated from top to bottom until one of them returns true and - then its associated body expression is evaluated. The idea, quite simply, is to have a - control-flow structure that visually resembles an ordinary pattern match, but where there is - no match value. - </p> - - <p> - In hind-sight, the <code>switch</code> expression is nothing more than a - glorified <code>if-then-else-if</code> construct that does not carry its own weight. - It is an expenditure on the complexity and strangeness budget that offers almost no gain - over using plain <code>if-then-else-if</code>. Moreover, it is error-prone, because it lacks - and explicit <code>else</code> branch in case none of the conditions evaluate to true. We - plan to remove it in future versions of Flix. - </p> - - <h5>String Concatenation with Plus</h5> - - <p> - Like most contemporary languages, Flix uses <code>+</code> for string concatenation. While - this is an uncontroversial design choice, it does not make much sense since strings are not - commutative, e.g. <code>"abc" + "def"</code> is <i>not</i> the same as <code>"def" + - "abc"</code>. A better alternative would be to use <code>++</code> as in Haskell. However, I - believe an even better design choice would be to forgo string concatenation and - instead rely entirely on string interpolation. String interpolation is a much more powerful - and elegant solution to the problem of building complex strings. - </p> - - <h2>Design Flaws No Longer Present in Flix</h2> - - <p> - The following design flaws have been fixed. - </p> - - <h5>Compilation of Option to Null</h5> - - <p> - Flix compiles to JVM bytecode and runs on the virtual machine. An earlier version of Flix - had an optimization that would take the <code>Option</code> enum: - </p> - - <InlineEditor> - {`Option[a] { + </InlineEditor> + + <p> + where the boolean expressions <code>cond1</code>, <code>cond2</code>, and <code>cond3</code> are evaluated + from top to bottom until one of them returns true and then its associated body expression is evaluated. + The idea, quite simply, is to have a control-flow structure that visually resembles an ordinary pattern + match, but where there is no match value. + </p> + + <p> + In hind-sight, the <code>switch</code> expression is nothing more than a glorified{' '} + <code>if-then-else-if</code> construct that does not carry its own weight. It is an expenditure on the + complexity and strangeness budget that offers almost no gain over using plain <code>if-then-else-if</code> + . Moreover, it is error-prone, because it lacks and explicit <code>else</code> branch in case none of the + conditions evaluate to true. We plan to remove it in future versions of Flix. + </p> + + <h5>String Concatenation with Plus</h5> + + <p> + Like most contemporary languages, Flix uses <code>+</code> for string concatenation. While this is an + uncontroversial design choice, it does not make much sense since strings are not commutative, e.g.{' '} + <code>"abc" + "def"</code> is <i>not</i> the same as <code>"def" + "abc"</code>. A better alternative + would be to use <code>++</code> as in Haskell. However, I believe an even better design choice would be to + forgo string concatenation and instead rely entirely on string interpolation. String interpolation is a + much more powerful and elegant solution to the problem of building complex strings. + </p> + + <h2>Design Flaws No Longer Present in Flix</h2> + + <p>The following design flaws have been fixed.</p> + + <h5>Compilation of Option to Null</h5> + + <p> + Flix compiles to JVM bytecode and runs on the virtual machine. An earlier version of Flix had an + optimization that would take the <code>Option</code> enum: + </p> + + <InlineEditor> + {`Option[a] { case None, case Some(a) }`} - </InlineEditor> - - <p> - and compile the <code>None</code> value to <code>null</code> and <code>Some(a)</code> to - the underlying value of <code>a</code>. The idea was to save allocation and de-allocation - of <code>Some</code> values, speeding up evaluation. - </p> - - <p> - But, this screws up interoperability with Java libraries. In Java <code>null</code> might - be given a special meaning that is incompatible with the meaning <code>None</code>. For - example, certain Java collections cannot contain <code>null</code> and trying to - put <code>None</code> into one of these would raise an unexpected exception. Consequently, - Flix no longer has this optimization. - </p> - - <h5>Useless Library Functions</h5> - - <p> - Flix aims to have a robust standard library that avoids some of the pitfalls of other - standard libraries. We have been particularly focused on two aspects: (i) ensuring that - functions and types have consistent names, e.g. <code>map</code> is - named <code>map</code> for both <code>Option</code> and <code>List</code>, and (ii) to - avoid partial functions, such as <code>List.head</code> and <code>List.tail</code> which are - not defined for empty lists. - </p> - - <p> - Yet, despite these principles, we still managed to implement some problematic functions in - the library. For example, we used to have the - functions <code>Option.isNone</code> and <code>Options.isSome</code>. The problem with these - functions is that they are not really useful and they lead to brittle code. For - example, <i>if</i> <code>Options.isSome</code> returns <code>true</code> then that - information cannot be used to unwrap the option anyway. Thus such functions are not - really useful. - </p> - - <h2>Function Call Syntax</h2> - - <p> - Inspired by Scala, early versions of Flix did not always use parentheses to mark a - function call. For example, the function: - </p> - - <InlineEditor> - {`def f: Int32 = 21`} - </InlineEditor> - - <p> - could be called by writing: - </p> - - <InlineEditor> - {`def g: Int32 = f + 42 // returns 63`} - </InlineEditor> - - <p> - The problem with this design is at least two-fold: (i) it hides when a function is applied, - which is terrible in a language with side-effects, and (ii) how does one express the - closure of <code>f</code>? (In Scala the answer is to write <code>f _ </code>). - </p> - - <p> - Today, in Flix, the code is written as: - </p> - - - <InlineEditor> - {`def f(): Int32 = 21 + </InlineEditor> + + <p> + and compile the <code>None</code> value to <code>null</code> and <code>Some(a)</code> to the underlying + value of <code>a</code>. The idea was to save allocation and de-allocation of <code>Some</code> values, + speeding up evaluation. + </p> + + <p> + But, this screws up interoperability with Java libraries. In Java <code>null</code> might be given a + special meaning that is incompatible with the meaning <code>None</code>. For example, certain Java + collections cannot contain <code>null</code> and trying to put <code>None</code> into one of these would + raise an unexpected exception. Consequently, Flix no longer has this optimization. + </p> + + <h5>Useless Library Functions</h5> + + <p> + Flix aims to have a robust standard library that avoids some of the pitfalls of other standard libraries. + We have been particularly focused on two aspects: (i) ensuring that functions and types have consistent + names, e.g. <code>map</code> is named <code>map</code> for both <code>Option</code> and <code>List</code>, + and (ii) to avoid partial functions, such as <code>List.head</code> and <code>List.tail</code> which are + not defined for empty lists. + </p> + + <p> + Yet, despite these principles, we still managed to implement some problematic functions in the library. + For example, we used to have the functions <code>Option.isNone</code> and <code>Options.isSome</code>. The + problem with these functions is that they are not really useful and they lead to brittle code. For + example, <i>if</i> <code>Options.isSome</code> returns <code>true</code> then that information cannot be + used to unwrap the option anyway. Thus such functions are not really useful. + </p> + + <h2>Function Call Syntax</h2> + + <p> + Inspired by Scala, early versions of Flix did not always use parentheses to mark a function call. For + example, the function: + </p> + + <InlineEditor>{`def f: Int32 = 21`}</InlineEditor> + + <p>could be called by writing:</p> + + <InlineEditor>{`def g: Int32 = f + 42 // returns 63`}</InlineEditor> + + <p> + The problem with this design is at least two-fold: (i) it hides when a function is applied, which is + terrible in a language with side-effects, and (ii) how does one express the closure of <code>f</code>? (In + Scala the answer is to write <code>f _ </code>). + </p> + + <p>Today, in Flix, the code is written as:</p> + + <InlineEditor> + {`def f(): Int32 = 21 def g: Int32 = f() + 42 // returns 63`} - </InlineEditor> - - <p> - which makes it clear when there is a function call. - </p> - - <h5>Infix Type Application</h5> - - <p> - In Flix, a function <code>f</code> can be called with the - arguments <code>x</code> and <code>y</code> in three ways: In standard prefix-style <code>f(x, - y)</code>, in infix-style <code>x `f` y</code>, and in postfix-style <code>x.f(y)</code>. - The latter is also sometimes referred to as universal function call syntax. I personally - feel reasonably confident that all three styles are worth supporting. The postfix-style fits - well for function calls such as <code>a.length()</code> where - the <code>length</code> function feels closely associated with the receiver argument. The - infix-style fits well with user-defined binary operations such as <code>x `lub` - y</code> where <code>lub</code> is the least upper bound - of <code>x</code> and <code>y</code>. And of course the prefix-style is the standard way - to perform a function call. - </p> - - <p> - Type constructors, such as <code>Option</code> and <code>Result</code> can be thought of - a special type of functions. Hence, it makes sense that their syntax should mirror function - applications. For example, we can write the type - applications <code>Option[Int32]</code> and <code>Result[Int32, - Int32]</code> mirroring the prefix style of regular function applications. Similarly, for a - while, Flix supported infix and postfix <i>type applications</i>. That is, the former could - also be expressed as: <code>Int32.Option[]</code> and <code>Int32.Result[Int32]</code>, or even - as <code>Int32 `Result` Int32</code>. Thankfully, those days are gone. Striving for such - uniformity in every place does not seem worth it. - </p> - - <h5>Unit Tests that Manually Construct Abstract Syntax Trees</h5> - - <p> - The Flix compiler comes with more than 6,500 manually written unit tests. Each unit test is - a Flix function that performs some computation, often with an expected result. The unit - tests are expressed in Flix itself. For example: - </p> - - <InlineEditor> - {`@test + </InlineEditor> + + <p>which makes it clear when there is a function call.</p> + + <h5>Infix Type Application</h5> + + <p> + In Flix, a function <code>f</code> can be called with the arguments <code>x</code> and <code>y</code> in + three ways: In standard prefix-style <code>f(x, y)</code>, in infix-style <code>x `f` y</code>, and in + postfix-style <code>x.f(y)</code>. The latter is also sometimes referred to as universal function call + syntax. I personally feel reasonably confident that all three styles are worth supporting. The + postfix-style fits well for function calls such as <code>a.length()</code> where the <code>length</code>{' '} + function feels closely associated with the receiver argument. The infix-style fits well with user-defined + binary operations such as <code>x `lub` y</code> where <code>lub</code> is the least upper bound of{' '} + <code>x</code> and <code>y</code>. And of course the prefix-style is the standard way to perform a + function call. + </p> + + <p> + Type constructors, such as <code>Option</code> and <code>Result</code> can be thought of a special type of + functions. Hence, it makes sense that their syntax should mirror function applications. For example, we + can write the type applications <code>Option[Int32]</code> and <code>Result[Int32, Int32]</code> mirroring + the prefix style of regular function applications. Similarly, for a while, Flix supported infix and + postfix <i>type applications</i>. That is, the former could also be expressed as:{' '} + <code>Int32.Option[]</code> and <code>Int32.Result[Int32]</code>, or even as{' '} + <code>Int32 `Result` Int32</code>. Thankfully, those days are gone. Striving for such uniformity in every + place does not seem worth it. + </p> + + <h5>Unit Tests that Manually Construct Abstract Syntax Trees</h5> + + <p> + The Flix compiler comes with more than 6,500 manually written unit tests. Each unit test is a Flix + function that performs some computation, often with an expected result. The unit tests are expressed in + Flix itself. For example: + </p> + + <InlineEditor> + {`@test def testArrayStore01(): Unit = let x = [1]; x[0] = 42`} - </InlineEditor> + </InlineEditor> - <p> - In earlier versions of Flix such unit tests were expressed by manually constructing "small" - abstract syntax tree fragments. For example, the above test would be expressed as something - like: - </p> + <p> + In earlier versions of Flix such unit tests were expressed by manually constructing "small" abstract + syntax tree fragments. For example, the above test would be expressed as something like: + </p> - <InlineEditor> - {`Let(Var("x", ...), ArrayNew(...), ArrayStore(Var("x"), Int32(0), Int32(42)))`} - </InlineEditor> + <InlineEditor> + {`Let(Var("x", ...), ArrayNew(...), ArrayStore(Var("x"), Int32(0), Int32(42)))`} + </InlineEditor> - <p> - The problem with such tests is at least two-fold: (i) the tests turn out to be anything - but small and (ii) maintenance becomes an absolute nightmare. I found that the surface - syntax of Flix has remained relatively stable over time, but the abstract syntax trees - have changed frequently, making maintenance of such test cases tedious and time - consuming. - </p> + <p> + The problem with such tests is at least two-fold: (i) the tests turn out to be anything but small and (ii) + maintenance becomes an absolute nightmare. I found that the surface syntax of Flix has remained relatively + stable over time, but the abstract syntax trees have changed frequently, making maintenance of such test + cases tedious and time consuming. + </p> - <h2>Bad Ideas that were Never Implemented</h2> + <h2>Bad Ideas that were Never Implemented</h2> - <p> - These ideas were fortunately never implemented in Flix. - </p> + <p>These ideas were fortunately never implemented in Flix.</p> - <h5>The Itself Keyword</h5> + <h5>The Itself Keyword</h5> - <p> - The idea was to introduce a special keyword that within a pattern match would refer to - the match value. For example: - </p> + <p> + The idea was to introduce a special keyword that within a pattern match would refer to the match value. + For example: + </p> - <InlineEditor> - {`def foo(e: Exp): Exp = match e { + <InlineEditor> + {`def foo(e: Exp): Exp = match e { // ... many lines ... case IfThenElse(e1, e2, e3) => itself // refers to the value of e. }`} - </InlineEditor> - - <p> - The keyword <code>itself</code> refers to the value of the match expression, i.e. the - value of <code>e</code>. The idea was that in very large and complicated pattern matches, - with many local variables, the <code>itself</code> keyword could always be used to refer to - the innermost match value. The thinking was that this would make it easier to avoid mistakes - such as returning <code>e0</code> instead of <code>e</code> or the like. - </p> - - <p> - The problem with this idea is at least three-fold: (i) it seems like overkill for a very - specific problem, (ii) it is not worth it on the complexity and strangeness - budget, and finally (iii) it is still brittle in the presence of nested pattern matches. - </p> - - <h2>Potential Design Flaws</h2> - - <p> - It is debatable whether the following feature is a design flaw or not. - </p> - - <h5> Built-in Syntax for Lists, Sets, and Maps </h5> - - <p> - Flix has a principle that states that the standard library should not be "blessed". - That is, the standard library should be independent of the Flix compiler and language. - It should just be like any other library: A collection of Flix code. - </p> - - <p> - Yet, despite this principle, Flix has special syntax for Lists, Sets and Maps: - </p> - - <InlineEditor> - {`1 :: 2 :: Nil + </InlineEditor> + + <p> + The keyword <code>itself</code> refers to the value of the match expression, i.e. the value of{' '} + <code>e</code>. The idea was that in very large and complicated pattern matches, with many local + variables, the <code>itself</code> keyword could always be used to refer to the innermost match value. The + thinking was that this would make it easier to avoid mistakes such as returning <code>e0</code> instead of{' '} + <code>e</code> or the like. + </p> + + <p> + The problem with this idea is at least three-fold: (i) it seems like overkill for a very specific problem, + (ii) it is not worth it on the complexity and strangeness budget, and finally (iii) it is still brittle in + the presence of nested pattern matches. + </p> + + <h2>Potential Design Flaws</h2> + + <p>It is debatable whether the following feature is a design flaw or not.</p> + + <h5> Built-in Syntax for Lists, Sets, and Maps </h5> + + <p> + Flix has a principle that states that the standard library should not be "blessed". That is, the standard + library should be independent of the Flix compiler and language. It should just be like any other library: + A collection of Flix code. + </p> + + <p>Yet, despite this principle, Flix has special syntax for Lists, Sets and Maps:</p> + + <InlineEditor> + {`1 :: 2 :: Nil Set#{1, 2, 3} Map#{1 -> 2, 3 -> 4}`} - </InlineEditor> - - <p> - which is built-in to the language. While technically these constructs are merely - syntactic sugar for <code>Cons</code>, and calls - to <code>Set.empty</code>, <code>Set.insert</code>, <code>Map.empty</code> and <code>Map.insert</code> there - is no getting around the fact that this is a special kind of blessing of the standard - library. In particular, it is <i>not</i> possible to define your - own <code>Foo#...</code> syntax for anything. - </p> - - </Col> - </Row> - </Container> - ) - } + </InlineEditor> + + <p> + which is built-in to the language. While technically these constructs are merely syntactic sugar for{' '} + <code>Cons</code>, and calls to <code>Set.empty</code>, <code>Set.insert</code>, <code>Map.empty</code>{' '} + and <code>Map.insert</code> there is no getting around the fact that this is a special kind of blessing of + the standard library. In particular, it is <i>not</i> possible to define your own <code>Foo#...</code>{' '} + syntax for anything. + </p> + </Col> + </Row> + </Container> + ) + } } export default DesignFlaws diff --git a/src/page/blog/Naming.js b/src/page/blog/Naming.js index a319502..db091e1 100644 --- a/src/page/blog/Naming.js +++ b/src/page/blog/Naming.js @@ -1,368 +1,338 @@ -import React, {Component} from "react"; -import {Card, CardText, CardTitle, Col, Container, Row} from "reactstrap"; -import InlineEditor from "../../util/InlineEditor"; +import React, { Component } from 'react' +import { Card, CardText, CardTitle, Col, Container, Row } from 'reactstrap' +import InlineEditor from '../../util/InlineEditor' class Naming extends Component { - - componentDidMount() { - document.title = "Flix | Naming Functional and Destructive Operations"; - } - - render() { - return ( - <Container style={{"text-align": "justify"}}> - <Row className="mb-3"> - <Col sm={12} md={8}> - - <h1>Naming Functional and Destructive Operations</h1> - - <p> - Posted April 2020 by <i>Magnus Madsen</i>. - </p> - - <p> - It has been said that there are only two hard problems in computer science: (i) naming, (ii) - cache invalidation, and (iii) off-by-one errors. In this blog post, I will explain a <i>name - consistency issue</i> that arises when a programming language wants to support both - functional and destructive operations. (A functional operation always returns new data, - whereas a destructive operation mutates existing data. For example, functionally reversing - an array returns a <i>new</i> array with its elements reversed, whereas destructively - reversing an array mutates the array in place.) - </p> - - <p> - Flix supports functional, imperative, and logic programming. Flix is intended to - be <i>functional-first</i> which simply means that if there is a trade-off between - having better functional- or imperative programming support, we tend to favor design choices - that support functional programming. For example, the Flix effect system separates pure - and impure functions mostly to the benefit of functional programming. - </p> - - <p> - Flix, being imperative, wants to support mutable data structures such as arrays, mutable - sets and maps. We have recently added support for all three. But let us for a moment - consider a simpler data structure: the humble list. - </p> - - <p> - We can <code>map</code> a function <code>f: a -{">"} b</code> over a list <code>l</code> to - obtain a new list of type <code>List[b]</code>: - </p> - - <InlineEditor> - {`def map(f: a -> b \\ ef, l: List[a]): List[b] \\ ef`} - </InlineEditor> - - <p> - (Here the <code>ef</code> denotes that the function is <i>effect polymorphic</i>, but that - is for another day.) - </p> - - <p> - We can also <code>map</code> a function over an option: - </p> - - <InlineEditor> - {`def map(f: a -> b \\ ef, o: Option[a]): Option[b] \\ ef`} - </InlineEditor> - - <p> - We can also <code>map</code> a function over an array: - </p> - - <InlineEditor> - {`def map(f: a -> b \\ ef, a: Array[a]): Array[b] \\ IO`} - </InlineEditor> - - <p> - This is good news: we can program with arrays in a functional-style. Mapping over an array - is certainly meaningful and useful. It might even be faster than mapping over a list! - Nevertheless, the main reason for having arrays (and mutable sets and maps) is to program - with them imperatively. We <i>want</i> to have operations that <i>mutate</i> their data. - </p> - - <p> - We want an operation that applies a function to every element of an array <i>changing - it in place</i>. <b>What should such an operation be called?</b> We cannot name - it <code>map</code> because that name is already taken by the functional version. - Let us simply call it <code>mapInPlace</code> for now: - </p> - - <InlineEditor> - {`def mapInPlace(f: a -> a \\ ef, a: Array[a]): Unit \\ IO`} - </InlineEditor> - - <p> - The signature of <code>mapInPlace</code> is different from the signature - of <code>map</code> in two important ways: - - <ul> - <li>The function returns <code>Unit</code> instead of returning an array.</li> - <li>The function takes an argument of type <code>a -{">"} a</code> rather than a function of - type <code>a -{">"} b</code>. - </li> - </ul> - </p> - - <p> - The latter is required because the type of an array is fixed. An array of bytes cannot - be replaced by an array of strings. Consequently, <code>mapInPlace</code> must take a - less generic function of type <code>a -{">"} a</code>. - </p> - - <p> - We have seen that it is useful to have both functional and destructive functions such - as <code>map</code> and <code>mapInPlace</code>, but what should such functions be called? - Are they sufficiently similar that they should share similar names? What should be the - general rule for naming functional operations and their counter-part destructive operations? - </p> - - <p> - To answer these questions, we surveyed the Flix standard library to understand what - names are currently being used. The table below shows a small cross section of the results: - </p> - - <p> - <table className="table table-striped small"> - <thead> - <tr> - <th scope="col">Functional Operation</th> - <th scope="col">Destructive Equivalent</th> - </tr> - </thead> - <tbody> - <tr> - <td>Array.map</td> - <td>Array.mapInPlace</td> - </tr> - <tr> - <td>Array.reverse</td> - <td>Array.reverseInPlace</td> - </tr> - <tr> - <td><i>missing</i></td> - <td>Array.sortByInPlace</td> - </tr> - <tr> - <td>Set.insert</td> - <td>not relevant – immutable</td> - </tr> - <tr> - <td>Set.union</td> - <td>not relevant – immutable</td> - </tr> - <tr> - <td><i>missing</i></td> - <td>MutSet.add</td> - </tr> - <tr> - <td><i>missing</i></td> - <td>MutSet.addAll</td> - </tr> - <tr> - <td>MutSet.map</td> - <td>MutSet.transform</td> - </tr> - </tbody> - </table> - </p> - - <p> - The table exposes the lack of any established naming convention. Let us consider some of the - many inconsistencies: For arrays, the functional and destructive operations are - named <code>Array.map</code> and <code>Array.mapInPlace</code>, but for mutable sets the - operations are named <code>MutSet.map</code> and <code>MutSet.transform</code>. - As another example, for immutable sets, we - have <code>Set.insert</code> and <code>Set.union</code>, but these - functional operations are missing on the mutable set. Moreover, the mutable version - of <code>Set.union</code> is called <code>Set.addAll</code>. - Finally, <code>Array.sortByInPlace</code>, what a name! - </p> - - <h2>Exploring the Design Space</h2> - - <p> - With these examples in mind, we tried to come up with a principled approach to naming. Our - exploration ended up with the following options: - </p> - - <Card body className="mb-3"> - <CardTitle>Option I: Distinct names</CardTitle> - <CardText> - <b>Proposal:</b> We give distinct names to functional and destructive operations. For - example, we will have <code>Array.map</code> and <code>Array.transform</code>, - and <code>MutSet.union</code> and <code>MutSet.addAll</code>. We reserve the most - common names (e.g. <code>map</code>) for the functional operations. - </CardText> - <CardText> - <b>Discussion:</b> With distinct names there is little room for confusion, but it may be - difficult to come up with meaningful names. For example, what should the - destructive version of <code>reverse</code> be called? - </CardText> - </Card> - - <Card body className="mb-3"> - <CardTitle>Option II: Use similar names but with a prefix or suffix</CardTitle> - <CardText> - <b>Proposal:</b> We reuse names between functional and destructive operations. To - distinguish operations, we add a prefix or suffix to the name. For - example, <code>reverseInPlace</code>, <code>inPlaceReverse</code>, <code>reverseMut</code>, - or similar. - </CardText> - <CardText> - <b>Discussion:</b> The advantage of this approach is that names are immediately - consistent. The disadvantages are that: (i) it may be difficult to come up with a good - prefix or suffix word, (ii) some users may dislike the chosen prefix or suffix, and - (iii) it may be confusing that the signatures for two similarly named operations differ - not only in the return type, but also in the polymorphism of the arguments. - </CardText> - </Card> - - <Card body className="mb-3"> - <CardTitle>Option III: Use similar names but with a prefix or suffix symbol</CardTitle> - <CardText> - <b>Proposal:</b> Similar to the previous proposal, but instead we use a symbol. For - example: <code>reverse!</code>, <code>reverse*</code>, or the like. - </CardText> - <CardText> - <b>Discussion:</b> The same advantages and disadvantages of the previous proposal, but - with the difference that using a symbol may be more or less appealing to programmers. - </CardText> - </Card> - - <Card body className="mb-3"> - <CardTitle>Option IV: Use namespaces</CardTitle> - <CardText> - <b>Proposal:</b> We place all functional operations into one namespace and all - destructive operations into another. For example, we might - have <code>Array.reverse</code> and <code>MutArray.reverse</code>. - </CardText> - <CardText> - <b>Discussion:</b> While this solution appears simple, it has two downsides: (i) we now - have multiple functions named <code>reverse</code> with different semantics and (ii) we - get a plethora of namespaces for data structures that exist in both - immutable and mutable variants. For example, we might end up - with <code>Set.map</code> (functional map on an immutable - set), <code>MutSet.Mut.map</code> (destructive map on a mutable set), - and <code>MutSet.Imm.map</code> (functional map on a mutable set). - </CardText> - </Card> - - <Card body className="mb-3"> - <CardTitle>Option V: The Python approach: sort vs. sorted</CardTitle> - <CardText> - <b>Proposal:</b> In Python the <code>sorted</code> operation functionally returns a new - sorted list whereas the <code>sort</code> operation destructively sorts a list in place. - We use the same scheme - for <code>reverse</code> and <code>reversed</code>, <code>map</code> and <code>mapped</code>, - and so forth. - </CardText> - <CardText> - <b>Discussion:</b> An internet search reveals that many programmers are puzzled by the - Python naming scheme. Another disadvantage is that the common functional names, - e.g. <code>map</code> and <code>reverse</code> would be reserved for destructive - operations (unless we adopt the <i>opposite</i> convention of Python). - </CardText> - </Card> - - <Card body className="mb-3"> - <CardTitle>Option VI: Drop functional operations for mutable data</CardTitle> - <CardText> - <b>Proposal:</b> We drop support for functional operations on mutable data structures. - If the user wants to map a function over an array, mutable set, or mutable - map he or she must first convert it to an immutable data structure. For example, to - functionally reverse an array one would - write <code>a.toList().reverse().toArray()</code>. - </CardText> - <CardText> - <b>Discussion:</b> The "stick your head in the sand approach". The programmer must - explicitly convert back and forth between immutable and mutable data structures. - While such an approach side-steps the naming issue, it is verbose and slow - (because we have to copy collections back and forth). Deliberately leaving functionality - out of the standard library does not mean that programmers will not miss it; instead we - are just passing the problem onto them. - </CardText> - </Card> - - <h2>The Principles</h2> - - <p> - We debated these options and slept on them for a few nights before we ultimately ended up - with the following hybrid principles: - </p> - - <Card body className="mb-3"> - <CardTitle>Library: Mutable Data is Functional Data</CardTitle> - <CardText> - In Flix, every mutable data structure supports functional operations. - For example, mutable collections, such - as <code>Array</code> and <code>MutSet</code> support - the <code>map</code> operation. Flix, being functional-first, reserves functional names - for functional operations. Across the standard library <code>map</code> has the same - name and the same type signature. - </CardText> - </Card> - - <Card body className="mb-3"> - <CardTitle>Library: Destructive Operations are Marked with '!'</CardTitle> - <CardText> - In Flix, every destructive operation is suffixed with an exclamation point. For - example, <code>Array.reverse(a)</code> returns a new array with the elements - of <code>a</code> in reverse order, whereas <code>Array.reverse!(a)</code> destructively - re-orders the elements of <code>a</code>. Note: This principle applies to destructive - operations that operate on data structures, not to impure functions in general, - e.g. <code>Console.printLine</code>. - </CardText> - </Card> - - <p> - As a side-note: Scheme has used <code>!</code> to indicate destructive operations for a - long-time. - </p> - - <Card body className="mb-3"> - <CardTitle>Library: Consistent Names of Functional and Destructive Operations</CardTitle> - <CardText> - In Flix, functional and destructive operations that share (i) similar behavior and (ii) - similar type signatures share similar names. For - example, <code>Array.reverse</code> and <code>Array.reverse!</code> share the - same name. On the other hand, <code>Array.transform!</code> is - called <code>transform!</code> and not <code>map!</code> because its type signature is - dissimilar to map (i.e. map works on functions of type <code>a -{">"} b</code>, but - transform requires functions of type <code>a -{">"} a</code>.) - </CardText> - </Card> - - <p> - We are in the process of refactoring the standard library to satisfy these new principles. - </p> - - <p> - Going forward, we are sensitive to at least four potential issues: - - <ul> - <li>Whether users come to like the aesthetics of names that end in exclamation point. - </li> - <li>If there is confusion about when exclamation points should be part of a name.</li> - <li>If there is confusion about when two operations should share the same name.</li> - <li>That Rust uses exclamation points for macro applications.</li> - </ul> - </p> - - <p> - As Flix continues to mature, we will keep an eye on these issues. - </p> - - <p> - Until next time, happy hacking. - </p> - - </Col> - </Row> - </Container> - ); - } - + componentDidMount() { + document.title = 'Flix | Naming Functional and Destructive Operations' + } + + render() { + return ( + <Container style={{ 'text-align': 'justify' }}> + <Row className="mb-3"> + <Col sm={12} md={8}> + <h1>Naming Functional and Destructive Operations</h1> + + <p> + Posted April 2020 by <i>Magnus Madsen</i>. + </p> + + <p> + It has been said that there are only two hard problems in computer science: (i) naming, (ii) cache + invalidation, and (iii) off-by-one errors. In this blog post, I will explain a{' '} + <i>name consistency issue</i> that arises when a programming language wants to support both functional and + destructive operations. (A functional operation always returns new data, whereas a destructive operation + mutates existing data. For example, functionally reversing an array returns a <i>new</i> array with its + elements reversed, whereas destructively reversing an array mutates the array in place.) + </p> + + <p> + Flix supports functional, imperative, and logic programming. Flix is intended to be{' '} + <i>functional-first</i> which simply means that if there is a trade-off between having better functional- + or imperative programming support, we tend to favor design choices that support functional programming. + For example, the Flix effect system separates pure and impure functions mostly to the benefit of + functional programming. + </p> + + <p> + Flix, being imperative, wants to support mutable data structures such as arrays, mutable sets and maps. We + have recently added support for all three. But let us for a moment consider a simpler data structure: the + humble list. + </p> + + <p> + We can <code>map</code> a function <code>f: a -{'>'} b</code> over a list <code>l</code> to obtain a new + list of type <code>List[b]</code>: + </p> + + <InlineEditor>{`def map(f: a -> b \\ ef, l: List[a]): List[b] \\ ef`}</InlineEditor> + + <p> + (Here the <code>ef</code> denotes that the function is <i>effect polymorphic</i>, but that is for another + day.) + </p> + + <p> + We can also <code>map</code> a function over an option: + </p> + + <InlineEditor>{`def map(f: a -> b \\ ef, o: Option[a]): Option[b] \\ ef`}</InlineEditor> + + <p> + We can also <code>map</code> a function over an array: + </p> + + <InlineEditor>{`def map(f: a -> b \\ ef, a: Array[a]): Array[b] \\ IO`}</InlineEditor> + + <p> + This is good news: we can program with arrays in a functional-style. Mapping over an array is certainly + meaningful and useful. It might even be faster than mapping over a list! Nevertheless, the main reason for + having arrays (and mutable sets and maps) is to program with them imperatively. We <i>want</i> to have + operations that <i>mutate</i> their data. + </p> + + <p> + We want an operation that applies a function to every element of an array <i>changing it in place</i>.{' '} + <b>What should such an operation be called?</b> We cannot name it <code>map</code> because that name is + already taken by the functional version. Let us simply call it <code>mapInPlace</code> for now: + </p> + + <InlineEditor>{`def mapInPlace(f: a -> a \\ ef, a: Array[a]): Unit \\ IO`}</InlineEditor> + + <p> + The signature of <code>mapInPlace</code> is different from the signature of <code>map</code> in two + important ways: + <ul> + <li> + The function returns <code>Unit</code> instead of returning an array. + </li> + <li> + The function takes an argument of type <code>a -{'>'} a</code> rather than a function of type{' '} + <code>a -{'>'} b</code>. + </li> + </ul> + </p> + + <p> + The latter is required because the type of an array is fixed. An array of bytes cannot be replaced by an + array of strings. Consequently, <code>mapInPlace</code> must take a less generic function of type{' '} + <code>a -{'>'} a</code>. + </p> + + <p> + We have seen that it is useful to have both functional and destructive functions such as <code>map</code>{' '} + and <code>mapInPlace</code>, but what should such functions be called? Are they sufficiently similar that + they should share similar names? What should be the general rule for naming functional operations and + their counter-part destructive operations? + </p> + + <p> + To answer these questions, we surveyed the Flix standard library to understand what names are currently + being used. The table below shows a small cross section of the results: + </p> + + <p> + <table className="table table-striped small"> + <thead> + <tr> + <th scope="col">Functional Operation</th> + <th scope="col">Destructive Equivalent</th> + </tr> + </thead> + <tbody> + <tr> + <td>Array.map</td> + <td>Array.mapInPlace</td> + </tr> + <tr> + <td>Array.reverse</td> + <td>Array.reverseInPlace</td> + </tr> + <tr> + <td> + <i>missing</i> + </td> + <td>Array.sortByInPlace</td> + </tr> + <tr> + <td>Set.insert</td> + <td>not relevant – immutable</td> + </tr> + <tr> + <td>Set.union</td> + <td>not relevant – immutable</td> + </tr> + <tr> + <td> + <i>missing</i> + </td> + <td>MutSet.add</td> + </tr> + <tr> + <td> + <i>missing</i> + </td> + <td>MutSet.addAll</td> + </tr> + <tr> + <td>MutSet.map</td> + <td>MutSet.transform</td> + </tr> + </tbody> + </table> + </p> + + <p> + The table exposes the lack of any established naming convention. Let us consider some of the many + inconsistencies: For arrays, the functional and destructive operations are named <code>Array.map</code>{' '} + and <code>Array.mapInPlace</code>, but for mutable sets the operations are named <code>MutSet.map</code>{' '} + and <code>MutSet.transform</code>. As another example, for immutable sets, we have <code>Set.insert</code>{' '} + and <code>Set.union</code>, but these functional operations are missing on the mutable set. Moreover, the + mutable version of <code>Set.union</code> is called <code>Set.addAll</code>. Finally,{' '} + <code>Array.sortByInPlace</code>, what a name! + </p> + + <h2>Exploring the Design Space</h2> + + <p> + With these examples in mind, we tried to come up with a principled approach to naming. Our exploration + ended up with the following options: + </p> + + <Card body className="mb-3"> + <CardTitle>Option I: Distinct names</CardTitle> + <CardText> + <b>Proposal:</b> We give distinct names to functional and destructive operations. For example, we will + have <code>Array.map</code> and <code>Array.transform</code>, and <code>MutSet.union</code> and{' '} + <code>MutSet.addAll</code>. We reserve the most common names (e.g. <code>map</code>) for the functional + operations. + </CardText> + <CardText> + <b>Discussion:</b> With distinct names there is little room for confusion, but it may be difficult to + come up with meaningful names. For example, what should the destructive version of <code>reverse</code>{' '} + be called? + </CardText> + </Card> + + <Card body className="mb-3"> + <CardTitle>Option II: Use similar names but with a prefix or suffix</CardTitle> + <CardText> + <b>Proposal:</b> We reuse names between functional and destructive operations. To distinguish + operations, we add a prefix or suffix to the name. For example, <code>reverseInPlace</code>,{' '} + <code>inPlaceReverse</code>, <code>reverseMut</code>, or similar. + </CardText> + <CardText> + <b>Discussion:</b> The advantage of this approach is that names are immediately consistent. The + disadvantages are that: (i) it may be difficult to come up with a good prefix or suffix word, (ii) some + users may dislike the chosen prefix or suffix, and (iii) it may be confusing that the signatures for two + similarly named operations differ not only in the return type, but also in the polymorphism of the + arguments. + </CardText> + </Card> + + <Card body className="mb-3"> + <CardTitle>Option III: Use similar names but with a prefix or suffix symbol</CardTitle> + <CardText> + <b>Proposal:</b> Similar to the previous proposal, but instead we use a symbol. For example:{' '} + <code>reverse!</code>, <code>reverse*</code>, or the like. + </CardText> + <CardText> + <b>Discussion:</b> The same advantages and disadvantages of the previous proposal, but with the + difference that using a symbol may be more or less appealing to programmers. + </CardText> + </Card> + + <Card body className="mb-3"> + <CardTitle>Option IV: Use namespaces</CardTitle> + <CardText> + <b>Proposal:</b> We place all functional operations into one namespace and all destructive operations + into another. For example, we might have <code>Array.reverse</code> and <code>MutArray.reverse</code>. + </CardText> + <CardText> + <b>Discussion:</b> While this solution appears simple, it has two downsides: (i) we now have multiple + functions named <code>reverse</code> with different semantics and (ii) we get a plethora of namespaces + for data structures that exist in both immutable and mutable variants. For example, we might end up with{' '} + <code>Set.map</code> (functional map on an immutable set), <code>MutSet.Mut.map</code> (destructive map + on a mutable set), and <code>MutSet.Imm.map</code> (functional map on a mutable set). + </CardText> + </Card> + + <Card body className="mb-3"> + <CardTitle>Option V: The Python approach: sort vs. sorted</CardTitle> + <CardText> + <b>Proposal:</b> In Python the <code>sorted</code> operation functionally returns a new sorted list + whereas the <code>sort</code> operation destructively sorts a list in place. We use the same scheme for{' '} + <code>reverse</code> and <code>reversed</code>, <code>map</code> and <code>mapped</code>, and so forth. + </CardText> + <CardText> + <b>Discussion:</b> An internet search reveals that many programmers are puzzled by the Python naming + scheme. Another disadvantage is that the common functional names, e.g. <code>map</code> and{' '} + <code>reverse</code> would be reserved for destructive operations (unless we adopt the <i>opposite</i>{' '} + convention of Python). + </CardText> + </Card> + + <Card body className="mb-3"> + <CardTitle>Option VI: Drop functional operations for mutable data</CardTitle> + <CardText> + <b>Proposal:</b> We drop support for functional operations on mutable data structures. If the user wants + to map a function over an array, mutable set, or mutable map he or she must first convert it to an + immutable data structure. For example, to functionally reverse an array one would write{' '} + <code>a.toList().reverse().toArray()</code>. + </CardText> + <CardText> + <b>Discussion:</b> The "stick your head in the sand approach". The programmer must explicitly convert + back and forth between immutable and mutable data structures. While such an approach side-steps the + naming issue, it is verbose and slow (because we have to copy collections back and forth). Deliberately + leaving functionality out of the standard library does not mean that programmers will not miss it; + instead we are just passing the problem onto them. + </CardText> + </Card> + + <h2>The Principles</h2> + + <p> + We debated these options and slept on them for a few nights before we ultimately ended up with the + following hybrid principles: + </p> + + <Card body className="mb-3"> + <CardTitle>Library: Mutable Data is Functional Data</CardTitle> + <CardText> + In Flix, every mutable data structure supports functional operations. For example, mutable collections, + such as <code>Array</code> and <code>MutSet</code> support the <code>map</code> operation. Flix, being + functional-first, reserves functional names for functional operations. Across the standard library{' '} + <code>map</code> has the same name and the same type signature. + </CardText> + </Card> + + <Card body className="mb-3"> + <CardTitle>Library: Destructive Operations are Marked with '!'</CardTitle> + <CardText> + In Flix, every destructive operation is suffixed with an exclamation point. For example,{' '} + <code>Array.reverse(a)</code> returns a new array with the elements of <code>a</code> in reverse order, + whereas <code>Array.reverse!(a)</code> destructively re-orders the elements of <code>a</code>. Note: + This principle applies to destructive operations that operate on data structures, not to impure + functions in general, e.g. <code>Console.printLine</code>. + </CardText> + </Card> + + <p> + As a side-note: Scheme has used <code>!</code> to indicate destructive operations for a long-time. + </p> + + <Card body className="mb-3"> + <CardTitle>Library: Consistent Names of Functional and Destructive Operations</CardTitle> + <CardText> + In Flix, functional and destructive operations that share (i) similar behavior and (ii) similar type + signatures share similar names. For example, <code>Array.reverse</code> and <code>Array.reverse!</code>{' '} + share the same name. On the other hand, <code>Array.transform!</code> is called <code>transform!</code>{' '} + and not <code>map!</code> because its type signature is dissimilar to map (i.e. map works on functions + of type <code>a -{'>'} b</code>, but transform requires functions of type <code>a -{'>'} a</code>.) + </CardText> + </Card> + + <p>We are in the process of refactoring the standard library to satisfy these new principles.</p> + + <p> + Going forward, we are sensitive to at least four potential issues: + <ul> + <li>Whether users come to like the aesthetics of names that end in exclamation point.</li> + <li>If there is confusion about when exclamation points should be part of a name.</li> + <li>If there is confusion about when two operations should share the same name.</li> + <li>That Rust uses exclamation points for macro applications.</li> + </ul> + </p> + + <p>As Flix continues to mature, we will keep an eye on these issues.</p> + + <p>Until next time, happy hacking.</p> + </Col> + </Row> + </Container> + ) + } } export default Naming diff --git a/src/page/blog/PolymorphicEffects.js b/src/page/blog/PolymorphicEffects.js index e161774..affd647 100644 --- a/src/page/blog/PolymorphicEffects.js +++ b/src/page/blog/PolymorphicEffects.js @@ -1,547 +1,470 @@ -import React, {Component} from "react"; -import {Col, Container, Row} from "reactstrap"; -import InlineEditor from "../../util/InlineEditor"; +import React, { Component } from 'react' +import { Col, Container, Row } from 'reactstrap' +import InlineEditor from '../../util/InlineEditor' class PolymorphicEffects extends Component { - - componentDidMount() { - document.title = "Flix | Taming Impurity with Polymorphic Effects"; - } - - render() { - return ( - <Container style={{"text-align": "justify"}}> - <Row className="mb-3"> - <Col sm={12} md={8}> - - <h1>Taming Impurity with Polymorphic Effects</h1> - - <p> - Posted May 2020 by <i>Magnus Madsen</i>. - </p> - - <p> - In the blog post <a - href="https://www.digitalmars.com/articles/b60.html">Patterns of Bugs</a>, Walter Bright, - the author of the <a href="https://dlang.org/">D programming Language</a>, writes about his - experience working at Boeing and their attitude towards failure: - </p> - - <blockquote className="blockquote"> - <p> - "[...] The best people have bad days and make mistakes, so the solution is to - change the process so the mistakes cannot happen or cannot propagate." - </p> - - <p> - "One simple example is an assembly that is bolted onto the frame with four bolts. The - obvious bolt pattern is a rectangle. Unfortunately, a rectangle pattern can be assembled - in two different ways, one of which is wrong. The solution is to offset one of the bolt - holes — then the assembly can only be bolted on in one orientation. The possible - mechanic's mistake is designed out of the system." - </p> - - <p> - "[...] <i>Parts can only be assembled one way, the correct - way.</i>" - </p> - </blockquote> - - <p> - (Emphasis mine). - </p> - - <p> - Bright continues to explain that these ideas are equally applicable to software: We should - build software such that it can only be assembled correctly. In this blog post, I will - discuss how this idea can be applied to the design of a type and effect system. In - particular, I will show how the Flix programming language and, by extension, its standard - library ensure that pure and impure functions are not assembled incorrectly. - </p> - - <h2>Impure Functional Programming</h2> - - <p> - A major selling point of functional programming is that it supports <a - href="https://wiki.haskell.org/Equational_reasoning_examples">equational reasoning</a>. - Informally, equational reasoning means that we can reason about programs by replacing an - expression by another one, provided they're both equal. For example, we can substitute - variables with the expressions they are bound to. - </p> - - <p> - For example, if we have the program fragment: - </p> - - <InlineEditor> - {`let x = 1 + 2; + componentDidMount() { + document.title = 'Flix | Taming Impurity with Polymorphic Effects' + } + + render() { + return ( + <Container style={{ 'text-align': 'justify' }}> + <Row className="mb-3"> + <Col sm={12} md={8}> + <h1>Taming Impurity with Polymorphic Effects</h1> + + <p> + Posted May 2020 by <i>Magnus Madsen</i>. + </p> + + <p> + In the blog post <a href="https://www.digitalmars.com/articles/b60.html">Patterns of Bugs</a>, Walter + Bright, the author of the <a href="https://dlang.org/">D programming Language</a>, writes about his + experience working at Boeing and their attitude towards failure: + </p> + + <blockquote className="blockquote"> + <p> + "[...] The best people have bad days and make mistakes, so the solution is to change the process so the + mistakes cannot happen or cannot propagate." + </p> + + <p> + "One simple example is an assembly that is bolted onto the frame with four bolts. The obvious bolt + pattern is a rectangle. Unfortunately, a rectangle pattern can be assembled in two different ways, one + of which is wrong. The solution is to offset one of the bolt holes — then the assembly can only be + bolted on in one orientation. The possible mechanic's mistake is designed out of the system." + </p> + + <p> + "[...] <i>Parts can only be assembled one way, the correct way.</i>" + </p> + </blockquote> + + <p>(Emphasis mine).</p> + + <p> + Bright continues to explain that these ideas are equally applicable to software: We should build software + such that it can only be assembled correctly. In this blog post, I will discuss how this idea can be + applied to the design of a type and effect system. In particular, I will show how the Flix programming + language and, by extension, its standard library ensure that pure and impure functions are not assembled + incorrectly. + </p> + + <h2>Impure Functional Programming</h2> + + <p> + A major selling point of functional programming is that it supports{' '} + <a href="https://wiki.haskell.org/Equational_reasoning_examples">equational reasoning</a>. Informally, + equational reasoning means that we can reason about programs by replacing an expression by another one, + provided they're both equal. For example, we can substitute variables with the expressions they are bound + to. + </p> + + <p>For example, if we have the program fragment:</p> + + <InlineEditor> + {`let x = 1 + 2; (x, x)`} - </InlineEditor> + </InlineEditor> - <p> - We can substitute for <code>x</code> and understand this program as: - </p> + <p> + We can substitute for <code>x</code> and understand this program as: + </p> - <InlineEditor> - {`(1 + 2, 1 + 2)`} - </InlineEditor> + <InlineEditor>{`(1 + 2, 1 + 2)`}</InlineEditor> - <p> - Unfortunately, in the presence of side-effects, such reasoning breaks down. - </p> + <p>Unfortunately, in the presence of side-effects, such reasoning breaks down.</p> - <p> - For example, the program fragment: - </p> + <p>For example, the program fragment:</p> - <InlineEditor> - {`let x = Console.printLine("Hello World"); + <InlineEditor> + {`let x = Console.printLine("Hello World"); (x, x)`} - </InlineEditor> - - <p> - is <i>not</i> equivalent to the program: - </p> - - <InlineEditor> - {`(Console.printLine("Hello World"), Console.printLine("Hello World"))`} - </InlineEditor> - - - <p> - Most contemporary functional programming languages, including Clojure, OCaml, and Scala, - forgo equational reasoning by allow arbitrary side-effects inside functions. To be clear, - it is still common to write purely functional programs in these languages and to reason - about them using equational reasoning. The major concern is that there is no language - support to guarantee when such reasoning is valid. Haskell is the only major programming - language that guarantees equational reasoning at the cost of a total and absolute ban on - side-effects. - </p> - - <p> - Flix aims to walk on the middle of the road: We want to support equational reasoning with - strong guarantees while still allowing side-effects. Our solution is a type and effect - system that cleanly separates pure and impure code. The idea of using an effect system - to separate pure and impure code is old, but our implementation, which supports type - inference and polymorphism, is new. - </p> - - <h2>Pure and Impure Functions</h2> - - <p> - Flix functions are pure by default. We can write a pure function: - </p> - - <InlineEditor> - {`def inc(x: Int): Int = x + 1`} - </InlineEditor> - - <p> - If we want to be explicit, but non-idiomatic, we can write: - </p> - - <InlineEditor> - {`def inc(x: Int): Int \\ {} = x + 1`} - </InlineEditor> - - <p> - where <code>\ {}</code> specifies that the <code>inc</code> function is pure. - </p> - - <p> - We can also write an impure function: - </p> - - <InlineEditor> - {`def sayHello(): Unit \\ IO = Console.printLine("Hello World!")`} - </InlineEditor> - - <p> - where <code>\ IO</code> specifies that the <code>sayHello</code> function is impure. - </p> - - <p> - The Flix type and effect system is <i>sound</i>, hence if we forget the <code>\ IO</code> annotation - on the <code>sayHello</code> function, the compiler will emit a type (or rather effect) error. - </p> - - <p> - The type and effect system cleanly separates pure and impure code. If an expression is pure - then it always evaluates to the same value and it cannot have side-effects. This is part - of what makes Flix functional-first: We can trust that pure functions behave like - mathematical functions. - </p> - - <p> - We have already seen that printing to the screen is impure. Other sources of impurity are - mutation of memory (e.g. writing to main memory, writing to the disk, writing to the - network, etc.). Reading from mutable memory is also impure because there is no guarantee - that we will get the same value if we read the same location twice. - </p> - - <p> - In Flix, the following operations are impure: - </p> - - <ul> - <li>Any use of channels (creating, sending, receiving, or selecting).</li> - <li>Any use of references (creating, accessing, or updating).</li> - <li>Any use of arrays (creating, accessing, updating, or slicing).</li> - <li>Any interaction with the Java world.</li> - </ul> - - <h2>Higher-Order Functions</h2> - - <p> - We can use the type and effect system to restrict the purity (or impurity) of function - arguments that are passed to higher-order functions. This is useful for at least two - reasons: (i) it prevents leaky abstractions where the caller can observe implementation - details of the callee, and (ii) it can help avoid bugs in the sense of Walter Bright's - "Parts can only be assembled one way, the correct way." - </p> - - <p> - We will now look at several examples of how type signatures can control purity or impurity. - </p> - - <p> - We can enforce that the predicate <code>f</code> passed - to <code>Set.exists</code> is <i>pure</i>: - </p> - - <InlineEditor> - {`def exists(f: a -> Bool, xs: Set[a]): Bool = ...`} - </InlineEditor> - - <p> - The signature <code>f: a -{">"} Bool</code> denotes a pure function - from <code>a</code> to <code>Bool</code>. Passing an impure function - to <code>exists</code> is a compile-time type error. We want to enforce - that <code>f</code> is pure because the contract for <code>exists</code> makes no guarantees - about how <code>f</code> is called. The implementation of <code>exists</code> may - call <code>f</code> on the elements in <code>xs</code> in any order and any number of times. - This requirement is <i>beneficial</i> because its allows freedom in the implementation - of <code>Set</code>, including in the choice of the underlying data structure and in the - implementation of its operations. For example, we can implement sets using search trees or - with hash tables, and we can perform existential queries in parallel using - fork-join. If <code>f</code> was impure such implementation details would leak and be - observable by the client. <i>Functions can only be assembled one way, the correct way.</i> - </p> - - <p> - We can enforce that the function <code>f</code> passed to the - function <code>List.foreach</code> is <i>impure</i>: - </p> - - <InlineEditor> - {`def foreach(f: a -> Unit \\ IO, xs: List[a]): Unit \\ IO = ...`} - </InlineEditor> - - <p> - The signature <code>f: a -{">"} Unit \ IO</code> denotes an impure function - from <code>b</code> to <code>Unit</code>. Passing a pure function to <code>foreach</code> is - a compile-time type error. Given that <code>f</code> is impure and <code>f</code> is called - within <code>foreach</code>, it is itself impure. We enforce that - the <code>f</code> function is impure because it is pointless to apply - a <i>pure</i> function with a <code>Unit</code> return type to every element of a list. <i>Functions - can only be assembled one way, the correct way.</i> - </p> - - <p> - We can enforce that event listeners are impure: - </p> - - <InlineEditor> - {`def onMouseDn(f: MouseEvent -> Unit \\ IO): Unit \\ IO = ... + </InlineEditor> + + <p> + is <i>not</i> equivalent to the program: + </p> + + <InlineEditor>{`(Console.printLine("Hello World"), Console.printLine("Hello World"))`}</InlineEditor> + + <p> + Most contemporary functional programming languages, including Clojure, OCaml, and Scala, forgo equational + reasoning by allow arbitrary side-effects inside functions. To be clear, it is still common to write + purely functional programs in these languages and to reason about them using equational reasoning. The + major concern is that there is no language support to guarantee when such reasoning is valid. Haskell is + the only major programming language that guarantees equational reasoning at the cost of a total and + absolute ban on side-effects. + </p> + + <p> + Flix aims to walk on the middle of the road: We want to support equational reasoning with strong + guarantees while still allowing side-effects. Our solution is a type and effect system that cleanly + separates pure and impure code. The idea of using an effect system to separate pure and impure code is + old, but our implementation, which supports type inference and polymorphism, is new. + </p> + + <h2>Pure and Impure Functions</h2> + + <p>Flix functions are pure by default. We can write a pure function:</p> + + <InlineEditor>{`def inc(x: Int): Int = x + 1`}</InlineEditor> + + <p>If we want to be explicit, but non-idiomatic, we can write:</p> + + <InlineEditor>{`def inc(x: Int): Int \\ {} = x + 1`}</InlineEditor> + + <p> + where <code>\ {}</code> specifies that the <code>inc</code> function is pure. + </p> + + <p>We can also write an impure function:</p> + + <InlineEditor>{`def sayHello(): Unit \\ IO = Console.printLine("Hello World!")`}</InlineEditor> + + <p> + where <code>\ IO</code> specifies that the <code>sayHello</code> function is impure. + </p> + + <p> + The Flix type and effect system is <i>sound</i>, hence if we forget the <code>\ IO</code> annotation on + the <code>sayHello</code> function, the compiler will emit a type (or rather effect) error. + </p> + + <p> + The type and effect system cleanly separates pure and impure code. If an expression is pure then it always + evaluates to the same value and it cannot have side-effects. This is part of what makes Flix + functional-first: We can trust that pure functions behave like mathematical functions. + </p> + + <p> + We have already seen that printing to the screen is impure. Other sources of impurity are mutation of + memory (e.g. writing to main memory, writing to the disk, writing to the network, etc.). Reading from + mutable memory is also impure because there is no guarantee that we will get the same value if we read the + same location twice. + </p> + + <p>In Flix, the following operations are impure:</p> + + <ul> + <li>Any use of channels (creating, sending, receiving, or selecting).</li> + <li>Any use of references (creating, accessing, or updating).</li> + <li>Any use of arrays (creating, accessing, updating, or slicing).</li> + <li>Any interaction with the Java world.</li> + </ul> + + <h2>Higher-Order Functions</h2> + + <p> + We can use the type and effect system to restrict the purity (or impurity) of function arguments that are + passed to higher-order functions. This is useful for at least two reasons: (i) it prevents leaky + abstractions where the caller can observe implementation details of the callee, and (ii) it can help avoid + bugs in the sense of Walter Bright's "Parts can only be assembled one way, the correct way." + </p> + + <p>We will now look at several examples of how type signatures can control purity or impurity.</p> + + <p> + We can enforce that the predicate <code>f</code> passed to <code>Set.exists</code> is <i>pure</i>: + </p> + + <InlineEditor>{`def exists(f: a -> Bool, xs: Set[a]): Bool = ...`}</InlineEditor> + + <p> + The signature <code>f: a -{'>'} Bool</code> denotes a pure function from <code>a</code> to{' '} + <code>Bool</code>. Passing an impure function to <code>exists</code> is a compile-time type error. We want + to enforce that <code>f</code> is pure because the contract for <code>exists</code> makes no guarantees + about how <code>f</code> is called. The implementation of <code>exists</code> may call <code>f</code> on + the elements in <code>xs</code> in any order and any number of times. This requirement is{' '} + <i>beneficial</i> because its allows freedom in the implementation of <code>Set</code>, including in the + choice of the underlying data structure and in the implementation of its operations. For example, we can + implement sets using search trees or with hash tables, and we can perform existential queries in parallel + using fork-join. If <code>f</code> was impure such implementation details would leak and be observable by + the client. <i>Functions can only be assembled one way, the correct way.</i> + </p> + + <p> + We can enforce that the function <code>f</code> passed to the function <code>List.foreach</code> is{' '} + <i>impure</i>: + </p> + + <InlineEditor>{`def foreach(f: a -> Unit \\ IO, xs: List[a]): Unit \\ IO = ...`}</InlineEditor> + + <p> + The signature <code>f: a -{'>'} Unit \ IO</code> denotes an impure function from <code>b</code> to{' '} + <code>Unit</code>. Passing a pure function to <code>foreach</code> is a compile-time type error. Given + that <code>f</code> is impure and <code>f</code> is called within <code>foreach</code>, it is itself + impure. We enforce that the <code>f</code> function is impure because it is pointless to apply a{' '} + <i>pure</i> function with a <code>Unit</code> return type to every element of a list.{' '} + <i>Functions can only be assembled one way, the correct way.</i> + </p> + + <p>We can enforce that event listeners are impure:</p> + + <InlineEditor> + {`def onMouseDn(f: MouseEvent -> Unit \\ IO): Unit \\ IO = ... def onMouseUp(f: MouseEvent -> Unit \\ IO): Unit \\ IO = ...`} - </InlineEditor> + </InlineEditor> - <p> - Event listeners are always executed for their side-effect: it would be pointless to register - a pure function as an event listener. - </p> + <p> + Event listeners are always executed for their side-effect: it would be pointless to register a pure + function as an event listener. + </p> - <p> - We can enforce that assertion and logging facilities are given pure functions: - </p> + <p>We can enforce that assertion and logging facilities are given pure functions:</p> - <InlineEditor> - {`def assert(f: Unit -> Bool): Unit = ... + <InlineEditor> + {`def assert(f: Unit -> Bool): Unit = ... def log(f: Unit -> String , l: LogLevel): Unit = ...`} - </InlineEditor> - - <p> - We want to support assertions and log statements that can be enabled and disabled at - run-time. For efficiency, it is critical that when assertions or logging is disabled, we do - not perform any computations that are redundant. We can achieve this by having the assert - and log functions take callbacks that are only invoked when required. A critical property of - these functions is that they must not influence the execution of the program. Otherwise, we - risk situations where enabling or disabling assertions or logging may impact the presence or - absence of a buggy execution. We can prevent such situations by requiring that the functions - passed to <code>assert</code> and <code>log</code> are pure. - </p> - - <p> - We can enforce that user-defined equality functions are pure. We want purity because the - programmer should not make any assumptions about how such functions are used. Moreover, most - collections (e.g. sets and maps) require that equality does not change over time to maintain - internal data structure invariants. Similar considerations apply to hash and comparator - functions. - </p> - - <p> - In the same spirit, we can enforce that one-shot comparator functions are pure: - </p> - - <InlineEditor> - {`def minBy(f: a -> b, l: List[a]): Option[a] = ... + </InlineEditor> + + <p> + We want to support assertions and log statements that can be enabled and disabled at run-time. For + efficiency, it is critical that when assertions or logging is disabled, we do not perform any computations + that are redundant. We can achieve this by having the assert and log functions take callbacks that are + only invoked when required. A critical property of these functions is that they must not influence the + execution of the program. Otherwise, we risk situations where enabling or disabling assertions or logging + may impact the presence or absence of a buggy execution. We can prevent such situations by requiring that + the functions passed to <code>assert</code> and <code>log</code> are pure. + </p> + + <p> + We can enforce that user-defined equality functions are pure. We want purity because the programmer should + not make any assumptions about how such functions are used. Moreover, most collections (e.g. sets and + maps) require that equality does not change over time to maintain internal data structure invariants. + Similar considerations apply to hash and comparator functions. + </p> + + <p>In the same spirit, we can enforce that one-shot comparator functions are pure:</p> + + <InlineEditor> + {`def minBy(f: a -> b, l: List[a]): Option[a] = ... def maxBy(f: a -> b, l: List[a]): Option[a] = ... def sortBy(f: a -> Int32, l: List[a]): List[a] = ... def groupBy(f: a -> k, l: List[a]): Map[k, List[a]] = ...`} - </InlineEditor> - - <p> - We can enforce that the <code>next</code> function passed - to <code>List.unfoldWithIter</code> is impure: - </p> - - <InlineEditor> - {`def unfoldWithIter(next: Unit -> Option[a] \\ IO): List[a] \\ IO`} - </InlineEditor> - - <p> - The unfoldWithIter function is a variant of the <code>unfoldWith</code> function where each - invocation of <code>next</code> changes some mutable state until the unfold completes. For - example, <code>unfoldWithIter</code> is frequently used to convert Java-style iterators into - lists. We want to enforce that <code>next</code> is impure because otherwise it is pointless - to use <code>unfoldWithIter</code>. If <code>next</code> is pure then it must always either - (i) return <code>None</code> which results in the empty list or (ii) - return <code>Some(v)</code> for a value <code>v</code> which would result in an infinite - execution. - </p> - - <p> - We can use purity to reject useless statement expressions. For example, the program: - </p> - - <InlineEditor> - {`def main(): Int = + </InlineEditor> + + <p> + We can enforce that the <code>next</code> function passed to <code>List.unfoldWithIter</code> is impure: + </p> + + <InlineEditor>{`def unfoldWithIter(next: Unit -> Option[a] \\ IO): List[a] \\ IO`}</InlineEditor> + + <p> + The unfoldWithIter function is a variant of the <code>unfoldWith</code> function where each invocation of{' '} + <code>next</code> changes some mutable state until the unfold completes. For example,{' '} + <code>unfoldWithIter</code> is frequently used to convert Java-style iterators into lists. We want to + enforce that <code>next</code> is impure because otherwise it is pointless to use{' '} + <code>unfoldWithIter</code>. If <code>next</code> is pure then it must always either (i) return{' '} + <code>None</code> which results in the empty list or (ii) return <code>Some(v)</code> for a value{' '} + <code>v</code> which would result in an infinite execution. + </p> + + <p>We can use purity to reject useless statement expressions. For example, the program:</p> + + <InlineEditor> + {`def main(): Int = List.map(x -> x + 1, 1 :: 2 :: Nil); 123`} - </InlineEditor> + </InlineEditor> - <p> - is rejected with the compiler error: - </p> + <p>is rejected with the compiler error:</p> - <InlineEditor> - {`-- Redundancy Error ------------------ foo.flix + <InlineEditor> + {`-- Redundancy Error ------------------ foo.flix >> Useless expression: It has no side-effect(s) and its result is discarded. 2 | List.map(x -> x + 1, 1 :: 2 :: Nil); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ useless expression.`} - </InlineEditor> - - <p> - Notice that the <code>List.map(...)</code> expression is pure because the function <code>x - -> x + 1</code> is pure. - </p> - - <h2>Polymorphic Effects</h2> - - <p> - Flix supports effect polymorphism which means that the effect of a higher-order function can - depend on the effects of its function arguments. - </p> - - <p> - For example, here is the type signature of <code>List.map</code>: - </p> - - <InlineEditor> - {`def map(f: a -> b \\ ef, xs: List[a]): List[b] \\ ef = ...`} - </InlineEditor> - - <p> - The syntax <code>f: a -{">"} b \ ef</code> denotes a function - from <code>a</code> to <code>b</code> with latent effect <code>ef</code>. The signature of - the <code>map</code> function captures that its - effect <code>ef</code> depends on the effect of its argument <code>f</code>. - That is, if <code>map</code> is called with a pure function then its evaluation is pure, - whereas if it is called with an impure function then its evaluation is impure. The effect - signature is <i>conservative</i> (i.e. over-approximate). That is, - the <code>map</code> function is considered impure even in the special case when the list is - empty and its execution is actually pure. - </p> - - <p> - The type and effect system can express combinations of effects using boolean operations. - We can, for example, express that forward function composition <code>>></code> is pure - if both its arguments are pure: - </p> - - <InlineEditor> - {` def >>(f: a -> b \\ ef1, g: b -> c \\ ef2): a -> c \\ { ef1, ef2 } = x -> g(f(x))`} - </InlineEditor> - - <p> - Here the function <code>f</code> has effect <code>ef1</code> and <code>g</code> has - effect <code>ef2</code>. The returned function has effect <code>ef1 and ef2</code>, i.e. for it - to be pure both <code>ef1</code> and <code>ef2</code> must be pure. Otherwise it is impure. - </p> - - <h2>Type Equivalences</h2> - - <p> - Let us take a short detour. - </p> - - <p> - In a purely functional programming language, such as Haskell, mapping two - functions <code>f</code> and <code>g</code> over a list <code>xs</code> is equivalent to - mapping their composition over the list. That is: - </p> - - <InlineEditor> - {`map(f, map(g, xs)) == map(f >> g, xs)`} - </InlineEditor> - - <p> - We can use such an equation to (automatically) rewrite the program to one that executes more - efficiently because the code on the right only traverses the list once and avoids - allocation of an intermediate list. Haskell already has support for such <a - href="https://wiki.haskell.org/GHC/Using_rules">rewrite rules</a> built into the language. - </p> - - <p> - It would be desirable if we could express the same rewrite rules for programming languages - such as Clojure, OCaml, and Scala. Unfortunately, identities - such as the above - do not - hold in the presence of side-effects. For example, the program: - </p> - - <InlineEditor> - {`let f = x -> {Console.printLine(x); x}; + </InlineEditor> + + <p> + Notice that the <code>List.map(...)</code> expression is pure because the function{' '} + <code>x -> x + 1</code> is pure. + </p> + + <h2>Polymorphic Effects</h2> + + <p> + Flix supports effect polymorphism which means that the effect of a higher-order function can depend on the + effects of its function arguments. + </p> + + <p> + For example, here is the type signature of <code>List.map</code>: + </p> + + <InlineEditor>{`def map(f: a -> b \\ ef, xs: List[a]): List[b] \\ ef = ...`}</InlineEditor> + + <p> + The syntax <code>f: a -{'>'} b \ ef</code> denotes a function from <code>a</code> to <code>b</code> with + latent effect <code>ef</code>. The signature of the <code>map</code> function captures that its effect{' '} + <code>ef</code> depends on the effect of its argument <code>f</code>. That is, if <code>map</code> is + called with a pure function then its evaluation is pure, whereas if it is called with an impure function + then its evaluation is impure. The effect signature is <i>conservative</i> (i.e. over-approximate). That + is, the <code>map</code> function is considered impure even in the special case when the list is empty and + its execution is actually pure. + </p> + + <p> + The type and effect system can express combinations of effects using boolean operations. We can, for + example, express that forward function composition <code>>></code> is pure if both its arguments are + pure: + </p> + + <InlineEditor> + {` def >>(f: a -> b \\ ef1, g: b -> c \\ ef2): a -> c \\ { ef1, ef2 } = x -> g(f(x))`} + </InlineEditor> + + <p> + Here the function <code>f</code> has effect <code>ef1</code> and <code>g</code> has effect{' '} + <code>ef2</code>. The returned function has effect <code>ef1 and ef2</code>, i.e. for it to be pure both{' '} + <code>ef1</code> and <code>ef2</code> must be pure. Otherwise it is impure. + </p> + + <h2>Type Equivalences</h2> + + <p>Let us take a short detour.</p> + + <p> + In a purely functional programming language, such as Haskell, mapping two functions <code>f</code> and{' '} + <code>g</code> over a list <code>xs</code> is equivalent to mapping their composition over the list. That + is: + </p> + + <InlineEditor>{`map(f, map(g, xs)) == map(f >> g, xs)`}</InlineEditor> + + <p> + We can use such an equation to (automatically) rewrite the program to one that executes more efficiently + because the code on the right only traverses the list once and avoids allocation of an intermediate list. + Haskell already has support for such <a href="https://wiki.haskell.org/GHC/Using_rules">rewrite rules</a>{' '} + built into the language. + </p> + + <p> + It would be desirable if we could express the same rewrite rules for programming languages such as + Clojure, OCaml, and Scala. Unfortunately, identities - such as the above - do not hold in the presence of + side-effects. For example, the program: + </p> + + <InlineEditor> + {`let f = x -> {Console.printLine(x); x}; let g = y -> {Console.printLine(y); y}; List.map(f, List.map(g, 1 :: 2 :: Nil))`} - </InlineEditor> - - <p> - prints <code>1, 2, 3, 1, 2, 3</code>. But, if we apply the rewrite rule, the transformed - program now prints <code>1, 1, 2, 2, 3, 3</code>! In the presence of side-effects we cannot - readily apply such rewrite rules. - </p> - - <p> - We can use the Flix type and effect to ensure that a rewrite rule like the above is only - applied when both <code>f</code> and <code>g</code> are pure! - </p> - - <p> - We can, in fact, go even further. If <i>at most - one</i> of <code>f</code> and <code>g</code> is impure then it is still safe to apply - the above rewrite rule. Furthermore, the Flix type and effect system is sufficiently - expressive to capture such a requirement! - </p> - - <p> - We can distill the essence of this point into the type signature: - </p> - - <InlineEditor> - {`def mapCompose(f: a -> b \\ e1, g: b -> c \\ {{(not e1) or e2}}, xs: List[a]): ... = ...`} - </InlineEditor> - - <p> - It is not important exactly what <code>mapCompose</code> does (or even if it makes sense). - What is important is that it has a function signature that requires two function - arguments <code>f</code> and <code>g</code> of which at most one may be impure. - </p> - - <p> - To understand why, let us look closely at the signature of <code>mapCompose</code>: - </p> - - <InlineEditor> - {`def mapCompose(f: a -> b \\ e1, g: b -> c \\ {{(not e1) or e2}}, xs: List[a]): ... = ...`} - </InlineEditor> - - <p> - <ul> - <li> - If <code>e1 = T</code> (i.e. <code>f</code> is pure) then <code>(not e1) or e2 = F - or e2 = e2</code>. In other words, <code>g</code> may be pure or impure. Its purity - is not constrained by the type signature. - </li> - <li> - If, on the other hand, <code>e1 = F</code> (i.e. <code>f</code> is impure) - then <code>(not e1) or e2 = T or e2 = T </code>. - In other words, <code>g</code> <i>must</i> be pure, otherwise there is a type error. - </li> - </ul> - </p> - - <p> - If you think about it, the above is equivalent to the requirement that at most one - of <code>f</code> and <code>g</code> may be impure. - </p> - - <p> - Without going into detail, an interesting aspect of the type and effect system is - that we might as well have given <code>mapCompose</code> the equivalent (equi-most general) - type signature: - </p> - - <InlineEditor> - {`def mapCompose(f: a -> b \\ {{(not e1) or e2}}, g: b -> c \\ e1, xs: List[a]): ... = ...`} - </InlineEditor> - - <p> - where the effects of <code>f</code> and <code>g</code> are swapped. - </p> - - <h2>Benign Impurity</h2> - - <p> - It is not uncommon for functions to be internally impure but observationally pure. - That is, a function may use mutation and perform side-effects without it being observable - by the external world. We say that such side-effects are <i>benign</i>. Fortunately, we can - still treat such functions as pure with an explicit <i>effect cast</i>. - </p> - - <p> - For example, we can call a Java method (which may have arbitrary side-effects) but - explicitly mark it as pure with an effect cast: - </p> - - <InlineEditor> - {`/// + </InlineEditor> + + <p> + prints <code>1, 2, 3, 1, 2, 3</code>. But, if we apply the rewrite rule, the transformed program now + prints <code>1, 1, 2, 2, 3, 3</code>! In the presence of side-effects we cannot readily apply such rewrite + rules. + </p> + + <p> + We can use the Flix type and effect to ensure that a rewrite rule like the above is only applied when both{' '} + <code>f</code> and <code>g</code> are pure! + </p> + + <p> + We can, in fact, go even further. If <i>at most one</i> of <code>f</code> and <code>g</code> is impure + then it is still safe to apply the above rewrite rule. Furthermore, the Flix type and effect system is + sufficiently expressive to capture such a requirement! + </p> + + <p>We can distill the essence of this point into the type signature:</p> + + <InlineEditor> + {`def mapCompose(f: a -> b \\ e1, g: b -> c \\ {{(not e1) or e2}}, xs: List[a]): ... = ...`} + </InlineEditor> + + <p> + It is not important exactly what <code>mapCompose</code> does (or even if it makes sense). What is + important is that it has a function signature that requires two function arguments <code>f</code> and{' '} + <code>g</code> of which at most one may be impure. + </p> + + <p> + To understand why, let us look closely at the signature of <code>mapCompose</code>: + </p> + + <InlineEditor> + {`def mapCompose(f: a -> b \\ e1, g: b -> c \\ {{(not e1) or e2}}, xs: List[a]): ... = ...`} + </InlineEditor> + + <p> + <ul> + <li> + If <code>e1 = T</code> (i.e. <code>f</code> is pure) then <code>(not e1) or e2 = F or e2 = e2</code>. + In other words, <code>g</code> may be pure or impure. Its purity is not constrained by the type + signature. + </li> + <li> + If, on the other hand, <code>e1 = F</code> (i.e. <code>f</code> is impure) then{' '} + <code>(not e1) or e2 = T or e2 = T </code>. In other words, <code>g</code> <i>must</i> be pure, + otherwise there is a type error. + </li> + </ul> + </p> + + <p> + If you think about it, the above is equivalent to the requirement that at most one of <code>f</code> and{' '} + <code>g</code> may be impure. + </p> + + <p> + Without going into detail, an interesting aspect of the type and effect system is that we might as well + have given <code>mapCompose</code> the equivalent (equi-most general) type signature: + </p> + + <InlineEditor> + {`def mapCompose(f: a -> b \\ {{(not e1) or e2}}, g: b -> c \\ e1, xs: List[a]): ... = ...`} + </InlineEditor> + + <p> + where the effects of <code>f</code> and <code>g</code> are swapped. + </p> + + <h2>Benign Impurity</h2> + + <p> + It is not uncommon for functions to be internally impure but observationally pure. That is, a function may + use mutation and perform side-effects without it being observable by the external world. We say that such + side-effects are <i>benign</i>. Fortunately, we can still treat such functions as pure with an explicit{' '} + <i>effect cast</i>. + </p> + + <p> + For example, we can call a Java method (which may have arbitrary side-effects) but explicitly mark it as + pure with an effect cast: + </p> + + <InlineEditor> + {`/// /// Returns the character at position \`i\` in the string \`s\`. /// def charAt(i: Int, s: String): Char = import java.lang.String.charAt(Int32); s.charAt(i) as \\ {}`} - </InlineEditor> - - <p> - We know that <code>java.lang.String.charAt</code> has is pure hence the cast is safe. - </p> - - <p> - An effect cast, like an ordinary cast, must be used with care. A cast is a mechanism - that allows the programmer to subvert the type (and effect) system. It is the - responsibility of the programmer to ensure that the cast is safe. Unlike type casts, an - effect cast cannot be checked at run-time with the consequence that an unsound effect cast - may silently lead to undefined behavior. - </p> - - <p> - Here is an example of a pure function that is implemented internally using mutation: - </p> - - <InlineEditor> - {`/// + </InlineEditor> + + <p> + We know that <code>java.lang.String.charAt</code> has is pure hence the cast is safe. + </p> + + <p> + An effect cast, like an ordinary cast, must be used with care. A cast is a mechanism that allows the + programmer to subvert the type (and effect) system. It is the responsibility of the programmer to ensure + that the cast is safe. Unlike type casts, an effect cast cannot be checked at run-time with the + consequence that an unsound effect cast may silently lead to undefined behavior. + </p> + + <p>Here is an example of a pure function that is implemented internally using mutation:</p> + + <InlineEditor> + {`/// /// Strip every indented line in string \`s\` by \`n\` spaces. \`n\` must be greater than \`0\`. /// Note, tabs are counted as a single space. /// @@ -565,56 +488,50 @@ def stripIndentHelper(n: Int32, s: String): String \\ IO = }; List.foreach(step, lines(s)); StringBuilder.toString(sb)`} - </InlineEditor> - - <p> - Internally, <code>stripIndentHelper</code> uses a mutable string builder. - </p> - - <h2>Type Inference and Boolean Unification</h2> - - <p> - The Flix type and effect system supports inference. Explicit type annotations are never - required locally within a function. As a design choice, we do require type signatures for - top-level definitions. Within a function, the programmer never has to worry about pure and - impure expressions; the compiler automatically infers whether an expression is pure, impure, - or effect polymorphic. The programmer only has to ensure that the declared type and effect - matches the type and effect of the function body. - </p> - - <p> - The details of the type and effect system are the subject of a forthcoming research paper - and will be made available in due time. - </p> - - <h2>Closing Thoughts</h2> - - <p> - The Flix type and effect system separates pure and impure code. The upshot is that a - functional programmer can trust that a pure function behaves like a mathematical function: - it returns the same result when given the same arguments. At the same time, we are still - allowed to write parts of the program in an impure, imperative style. Effect polymorphism - ensures that both pure and impure code can be used with higher-order functions. - </p> - - <p> - We can also use effects to control when higher-order functions require pure (or impure) - functions. We have seen several examples of such use cases, e.g. requiring - that <code>Set.count</code> takes a pure function or - that <code>List.unfoldWithIter</code> takes an impure function. Together, these restrictions - ensure that functions can only be assembled in one way, the correct way. - </p> - - <p> - Until next time, happy hacking. - </p> - - </Col> - </Row> - </Container> - ); - } - + </InlineEditor> + + <p> + Internally, <code>stripIndentHelper</code> uses a mutable string builder. + </p> + + <h2>Type Inference and Boolean Unification</h2> + + <p> + The Flix type and effect system supports inference. Explicit type annotations are never required locally + within a function. As a design choice, we do require type signatures for top-level definitions. Within a + function, the programmer never has to worry about pure and impure expressions; the compiler automatically + infers whether an expression is pure, impure, or effect polymorphic. The programmer only has to ensure + that the declared type and effect matches the type and effect of the function body. + </p> + + <p> + The details of the type and effect system are the subject of a forthcoming research paper and will be made + available in due time. + </p> + + <h2>Closing Thoughts</h2> + + <p> + The Flix type and effect system separates pure and impure code. The upshot is that a functional programmer + can trust that a pure function behaves like a mathematical function: it returns the same result when given + the same arguments. At the same time, we are still allowed to write parts of the program in an impure, + imperative style. Effect polymorphism ensures that both pure and impure code can be used with higher-order + functions. + </p> + + <p> + We can also use effects to control when higher-order functions require pure (or impure) functions. We have + seen several examples of such use cases, e.g. requiring that <code>Set.count</code> takes a pure function + or that <code>List.unfoldWithIter</code> takes an impure function. Together, these restrictions ensure + that functions can only be assembled in one way, the correct way. + </p> + + <p>Until next time, happy hacking.</p> + </Col> + </Row> + </Container> + ) + } } export default PolymorphicEffects diff --git a/src/page/blog/ProgrammingLanguageDefense.js b/src/page/blog/ProgrammingLanguageDefense.js index abe8282..d941644 100644 --- a/src/page/blog/ProgrammingLanguageDefense.js +++ b/src/page/blog/ProgrammingLanguageDefense.js @@ -1,341 +1,320 @@ -import React, {Component} from "react"; -import {Col, Container, Row} from "reactstrap"; -import {Link} from "react-router-dom"; +import React, { Component } from 'react' +import { Col, Container, Row } from 'reactstrap' +import { Link } from 'react-router-dom' class ProgrammingLanguageDefense extends Component { - - componentDidMount() { - document.title = "Flix | In Defense of Programming Languages"; - } - - render() { - return ( - <Container style={{"text-align": "justify"}}> - <Row className="mb-3"> - <Col sm={12} md={8}> - - <h1>In Defense of Programming Languages</h1> - - <p> - Posted July 2021 by <i>Magnus Madsen</i>. Thanks to Matthew Lutze for discussion and - comments on an early draft. - </p> - - <p> - This blog post is written in defense of programming language enthusiasts; whether they are - compiler hackers, programming language hobbyists, industry professionals, or academics. - </p> - - <p> - In this blog post, I want to examine the discourse around programming languages and - especially how new programming languages are received. My hope is to improve communication - between programming languages designers and software developers. I understand that - we cannot all agree, but it would be fantastic if everyone could at least try to be - friendly, to be intellectually curious, and to give constructive feedback! - </p> - - <h2>A Few Quotes from the Internet</h2> - - <p> - Let me set the stage with a few quotes from social media tech sites (e.g. Reddit, - HackerNews, Twitter, etc.). I have lightly edited and anonymized the following quotes: - </p> - - <blockquote className="blockquote text-center"> - <p className="mb-0">"Great! Yet-another-programming-language™. This is exactly what we - need; the gazillion of existing programming languages is not enough!"</p> - <footer className="blockquote-footer"><cite title="Source Title">Furious Panda</cite> via - Reddit - </footer> - </blockquote> - - <blockquote className="blockquote text-center"> - <p className="mb-0">"This is – by far – the worst syntax I have ever seen in a functional - language!"</p> - <footer className="blockquote-footer"><cite title="Source Title">Irate Penguin</cite> via - Reddit - </footer> - </blockquote> - - <blockquote className="blockquote text-center"> - <p className="mb-0">"The language is probably great from a technical point of view, but - unless Apple, Google, Mozilla, or Microsoft is on-board it is pointless."</p> - <footer className="blockquote-footer"><cite title="Source Title">Angry Beaver</cite> via - HackerNews - </footer> - </blockquote> - - <blockquote className="blockquote text-center"> - <p className="mb-0">"How can anyone understand such weird syntax? I hate all these - symbols."</p> - <footer className="blockquote-footer"><cite title="Source Title">Bitter - Turtle</cite> via Reddit - </footer> - </blockquote> - - <blockquote className="blockquote text-center"> - <p className="mb-0">"The examples all look horrible. The site looks horrible. This needs a - lot of work before it gets close to anything I would even consider using."</p> - <footer className="blockquote-footer"><cite title="Source Title">Enraged - Koala</cite> via Twitter - </footer> - </blockquote> - - <p> - While all of the above quotes are in response to news about the Flix programming language - (on whose website you are currently reading this blog post), depressingly similar comments - are frequently posted in response to news about other new programming languages. - </p> - - <p> - Why do people post such comments? And what can be done about it? - </p> - - <h2>Where do such comments come from?</h2> - - <p> - I think there are two reasons which are grounded in legitimate concerns: - </p> - - <p> - <ul> - <li> - <b>Fatigue:</b> I think there is a sense that there are new programming - languages coming out all the time. Paradoxically, I think there is both a dread of - having to keep up with ever-changing programming languages (and other technologies) - and simultaneously a sense that these new programming languages are all the same. - </li> - - <li> - <b>Speech:</b> Programming languages are the material with which we craft programs: - It is our way of "speaking" algorithmically. They are about what we say, how we say - it, and even what can be said. Like prose, what is beautiful and elegant is - in the eye of the beholder. It is not surprising then that when a new programming - language comes along and suggests a different form of expression that some may have - strong reactions to. - </li> - </ul> - </p> - - <p> - Of course there are also internet trolls; but let us ignore them. - </p> - - <h2>A Point-by-Point Rebuttal</h2> - - <p> - I want to give a point-by-point rebuttal to the most common refrains heard whenever a new - programming language is proposed. - </p> - - <h5>Do we really need new programming languages?</h5> - - <p> - The Flix <Link to="/faq/"> FAQ </Link> joking responds to this question with a rhetorical - question: <i>Do we really need safer airplanes? Do we really need electric cars? Do we - really need more ergonomic chairs?</i> - </p> - - <p> - I think it is a valid argument. We want better programming languages because we want to - offer software developers better tools to write their programs. You might say that existing - programming languages already have all the feature we need, but I think that there are - exciting developments; both brand new ideas and old research ideas that are making their - way into new programming languages: - </p> - - <p> - <ul> - <li> - <b>Safety:</b> region-based memory management, lifetimes, ownership types, linear - types, 2nd class values, and capabilities. - </li> - <li> - <b>Expressiveness:</b> union and intersection types, polymorphic effect systems, - algebraic effects, type-driven development, increasingly powerful type inference. - </li> - <li> - <b>Development Experience:</b> the Visual Studio Code ecosystem, the language server - protocol, GitHub code-spaces. - </li> - </ul> - </p> - - <p> - I don't think we are anywhere near to the point where programming languages are as good as - they are ever going to get. On the contrary, I think we are still in the infancy of - programming language design. - </p> - - <h5>All programming languages are the same</h5> - - <p> - I strongly disagree. I think we are experiencing a period of programming language - fragmentation after a long period of consolidation and stagnation. For the last 15-years or - so, the industry has been dominated by C, C++, C# and Java. The market share of these - programming languages was always increasing and they were the default safe choice for new - software projects. - </p> - - <p> - Today that is no longer the case. The ecosystem of programming languages is much more - diverse (and stronger for it). We have Rust. We have Scala. We also have Go, Python, and - JavaScript. There is also Crystal, Elixir, Elm, and Nim (Oh, and Flix of course!) We are in - a period of fragmentation. After a decade of object-oriented ossification we are entering a - new and exciting period! - </p> - - <p> - If history repeats itself then at some point we will enter a new period of consolidation. - It is too early to speculate on which programming languages will be the winners, but I feel - confident that they will be much better than C, C++, C#, and Java! (Ok, maybe C++30 will be - one of them – that language changes as much as Haskell!) - </p> - - <p> - (Addendum: That said, it is true that many hobby programming languages look the same. But - there is a reason for that: if you want to learn about compilers it makes sense to start by - implementing a minimal functional or object-oriented programming language.) - </p> - - <h5>New programming languages are too complicated!</h5> - - <p> - That's the way of the world. - </p> - - <p> - What do you think an airline pilot from the 1950's would say if he or she entered the flight - deck of an Airbus A350? Sure, the principles of flying are the same, and indeed iteration - and recursion are not going anywhere. But we cannot expect everything to stay the same. All - those instruments are there for a reason and they make flying safer and more efficient. - </p> - - <p> - As another example, once universities start teaching Rust (and we will!) then programming - with ownership and lifetimes will become commonplace. As yet another example, today every - programmer can reasonably be expected to know about <code>filter</code> and <code>map</code>, - but that was certainly not the case 15 years ago! - </p> - - <h5>A programming language cannot be successful unless a major tech company is behind it</h5> - - <p> - Historically that has not been true. Neither PHP, Python, Ruby, Rust, or Scala had - major tech companies behind them. If industry support came, it came at a later time. - </p> - - <h2>Ideas for Better Communication</h2> - - <p> - With these points in mind, I want to suggest some ways to improve communication between - aspiring programming language designers and software developers: - </p> - - <p> - When presenting a new programming language (or ideas related to a new language): - </p> - - <p> - <ul> - <li> - <b>Scope:</b> State the intended scope of the project. Is it a hobby project - made for fun? Is it an open source project hoping to gain traction? Is it a research - prototype? Is it a commercially backed project? What is the intended use case? Is - there a "killer-app"? - </li> - - <li> - <b>Implementation:</b> What has been implemented? A compiler? An interpreter? Do you - have a standard library? How big is it? How many lines is the project? - </li> - - <li> - <b>Novelty:</b> What is new in the programming language? Are there some new takes - on old ideas? Is there something novel? How is the language an improvement compared - to existing languages? Does the language make you think in a new way about - programming? - </li> - - <li> - <b>Resources:</b> What resources are behind the programming language? Is it a hobby - project? An open source project? An academic project? Are you open to collaboration? - Do you have backing (from industry or otherwise)? - </li> - - <li> - <b>Feedback:</b> What kind of feedback are you looking for? What other people think? - Suggestions for improvements and related work? Constructive criticism about the - design? What it would take for someone to consider using it? - </li> - - <li> - <b>Reality Check:</b> Try to avoid grandiose or unsubstantiated claims: Do your - compiler really outperform modern state-of-the-art C compilers? Is your type system - really more expressive than Haskell or Idris? Is your language really safer than - Ada? - </li> - </ul> - </p> - - <h2>What about Flix?</h2> - - <p> - The time has come to nail our colors to the flag: - </p> - - <p> - <ul> - <li> - <b>Scope:</b> We are building a real programming language intended for real-world - use. It is an open-source project lead by academic programming language researchers. - </li> - - <li> - <b>Implementation:</b> The Flix compiler project is ~137,000 lines of code. We have - a realistic compiler, a standard library (extensive, but still under development), a - Visual Studio Code extension (with auto-complete!), an online playground, online - documentation, and several published papers on the novel aspects of the language. - </li> - - <li> - <b>Novelty:</b> We have a whole page (<Link to="/innovations/">Innovations</Link>) - that covers this, but briefly: a unique combination of features, combined with - first-class Datalog constraints and a polymorphic effect system. - </li> - - <li> - <b>Resources:</b> We are a group of programming language researchers from Aarhus - University and the University of Waterloo together with a small community of open - source contributors. Through our research we have funding for working on Flix. - </li> - - <li> - <b>Feedback:</b> We want to know what people think about Flix, how we can make Flix - better, and what it would take for someone to consider using it. - </li> - - <li> - <b>Reality Check:</b> We aim to under-promise and over-deliver. We do not promote - features before they exist. Our typical pipeline is: (Research) Idea → - Implementation → Documentation → Presentation to the World. Development is not - secret; everything is on GitHub. We just don't promote anything before it is ready. - We have exciting things in the pipeline, but you will have to wait a bit before - learning about them (or spoil yourself by diving into the GitHub issues!) - </li> - </ul> - </p> - - <p> - Until next time, happy hacking. - </p> - - </Col> - </Row> - </Container> - ); - } - + componentDidMount() { + document.title = 'Flix | In Defense of Programming Languages' + } + + render() { + return ( + <Container style={{ 'text-align': 'justify' }}> + <Row className="mb-3"> + <Col sm={12} md={8}> + <h1>In Defense of Programming Languages</h1> + + <p> + Posted July 2021 by <i>Magnus Madsen</i>. Thanks to Matthew Lutze for discussion and comments on an early + draft. + </p> + + <p> + This blog post is written in defense of programming language enthusiasts; whether they are compiler + hackers, programming language hobbyists, industry professionals, or academics. + </p> + + <p> + In this blog post, I want to examine the discourse around programming languages and especially how new + programming languages are received. My hope is to improve communication between programming languages + designers and software developers. I understand that we cannot all agree, but it would be fantastic if + everyone could at least try to be friendly, to be intellectually curious, and to give constructive + feedback! + </p> + + <h2>A Few Quotes from the Internet</h2> + + <p> + Let me set the stage with a few quotes from social media tech sites (e.g. Reddit, HackerNews, Twitter, + etc.). I have lightly edited and anonymized the following quotes: + </p> + + <blockquote className="blockquote text-center"> + <p className="mb-0"> + "Great! Yet-another-programming-language™. This is exactly what we need; the gazillion of existing + programming languages is not enough!" + </p> + <footer className="blockquote-footer"> + <cite title="Source Title">Furious Panda</cite> via Reddit + </footer> + </blockquote> + + <blockquote className="blockquote text-center"> + <p className="mb-0">"This is – by far – the worst syntax I have ever seen in a functional language!"</p> + <footer className="blockquote-footer"> + <cite title="Source Title">Irate Penguin</cite> via Reddit + </footer> + </blockquote> + + <blockquote className="blockquote text-center"> + <p className="mb-0"> + "The language is probably great from a technical point of view, but unless Apple, Google, Mozilla, or + Microsoft is on-board it is pointless." + </p> + <footer className="blockquote-footer"> + <cite title="Source Title">Angry Beaver</cite> via HackerNews + </footer> + </blockquote> + + <blockquote className="blockquote text-center"> + <p className="mb-0">"How can anyone understand such weird syntax? I hate all these symbols."</p> + <footer className="blockquote-footer"> + <cite title="Source Title">Bitter Turtle</cite> via Reddit + </footer> + </blockquote> + + <blockquote className="blockquote text-center"> + <p className="mb-0"> + "The examples all look horrible. The site looks horrible. This needs a lot of work before it gets close + to anything I would even consider using." + </p> + <footer className="blockquote-footer"> + <cite title="Source Title">Enraged Koala</cite> via Twitter + </footer> + </blockquote> + + <p> + While all of the above quotes are in response to news about the Flix programming language (on whose + website you are currently reading this blog post), depressingly similar comments are frequently posted in + response to news about other new programming languages. + </p> + + <p>Why do people post such comments? And what can be done about it?</p> + + <h2>Where do such comments come from?</h2> + + <p>I think there are two reasons which are grounded in legitimate concerns:</p> + + <p> + <ul> + <li> + <b>Fatigue:</b> I think there is a sense that there are new programming languages coming out all the + time. Paradoxically, I think there is both a dread of having to keep up with ever-changing programming + languages (and other technologies) and simultaneously a sense that these new programming languages are + all the same. + </li> + + <li> + <b>Speech:</b> Programming languages are the material with which we craft programs: It is our way of + "speaking" algorithmically. They are about what we say, how we say it, and even what can be said. Like + prose, what is beautiful and elegant is in the eye of the beholder. It is not surprising then that + when a new programming language comes along and suggests a different form of expression that some may + have strong reactions to. + </li> + </ul> + </p> + + <p>Of course there are also internet trolls; but let us ignore them.</p> + + <h2>A Point-by-Point Rebuttal</h2> + + <p> + I want to give a point-by-point rebuttal to the most common refrains heard whenever a new programming + language is proposed. + </p> + + <h5>Do we really need new programming languages?</h5> + + <p> + The Flix <Link to="/faq/"> FAQ </Link> joking responds to this question with a rhetorical question:{' '} + <i> + Do we really need safer airplanes? Do we really need electric cars? Do we really need more ergonomic + chairs? + </i> + </p> + + <p> + I think it is a valid argument. We want better programming languages because we want to offer software + developers better tools to write their programs. You might say that existing programming languages already + have all the feature we need, but I think that there are exciting developments; both brand new ideas and + old research ideas that are making their way into new programming languages: + </p> + + <p> + <ul> + <li> + <b>Safety:</b> region-based memory management, lifetimes, ownership types, linear types, 2nd class + values, and capabilities. + </li> + <li> + <b>Expressiveness:</b> union and intersection types, polymorphic effect systems, algebraic effects, + type-driven development, increasingly powerful type inference. + </li> + <li> + <b>Development Experience:</b> the Visual Studio Code ecosystem, the language server protocol, GitHub + code-spaces. + </li> + </ul> + </p> + + <p> + I don't think we are anywhere near to the point where programming languages are as good as they are ever + going to get. On the contrary, I think we are still in the infancy of programming language design. + </p> + + <h5>All programming languages are the same</h5> + + <p> + I strongly disagree. I think we are experiencing a period of programming language fragmentation after a + long period of consolidation and stagnation. For the last 15-years or so, the industry has been dominated + by C, C++, C# and Java. The market share of these programming languages was always increasing and they + were the default safe choice for new software projects. + </p> + + <p> + Today that is no longer the case. The ecosystem of programming languages is much more diverse (and + stronger for it). We have Rust. We have Scala. We also have Go, Python, and JavaScript. There is also + Crystal, Elixir, Elm, and Nim (Oh, and Flix of course!) We are in a period of fragmentation. After a + decade of object-oriented ossification we are entering a new and exciting period! + </p> + + <p> + If history repeats itself then at some point we will enter a new period of consolidation. It is too early + to speculate on which programming languages will be the winners, but I feel confident that they will be + much better than C, C++, C#, and Java! (Ok, maybe C++30 will be one of them – that language changes + as much as Haskell!) + </p> + + <p> + (Addendum: That said, it is true that many hobby programming languages look the same. But there is a + reason for that: if you want to learn about compilers it makes sense to start by implementing a minimal + functional or object-oriented programming language.) + </p> + + <h5>New programming languages are too complicated!</h5> + + <p>That's the way of the world.</p> + + <p> + What do you think an airline pilot from the 1950's would say if he or she entered the flight deck of an + Airbus A350? Sure, the principles of flying are the same, and indeed iteration and recursion are not going + anywhere. But we cannot expect everything to stay the same. All those instruments are there for a reason + and they make flying safer and more efficient. + </p> + + <p> + As another example, once universities start teaching Rust (and we will!) then programming with ownership + and lifetimes will become commonplace. As yet another example, today every programmer can reasonably be + expected to know about <code>filter</code> and <code>map</code>, but that was certainly not the case 15 + years ago! + </p> + + <h5>A programming language cannot be successful unless a major tech company is behind it</h5> + + <p> + Historically that has not been true. Neither PHP, Python, Ruby, Rust, or Scala had major tech companies + behind them. If industry support came, it came at a later time. + </p> + + <h2>Ideas for Better Communication</h2> + + <p> + With these points in mind, I want to suggest some ways to improve communication between aspiring + programming language designers and software developers: + </p> + + <p>When presenting a new programming language (or ideas related to a new language):</p> + + <p> + <ul> + <li> + <b>Scope:</b> State the intended scope of the project. Is it a hobby project made for fun? Is it an + open source project hoping to gain traction? Is it a research prototype? Is it a commercially backed + project? What is the intended use case? Is there a "killer-app"? + </li> + + <li> + <b>Implementation:</b> What has been implemented? A compiler? An interpreter? Do you have a standard + library? How big is it? How many lines is the project? + </li> + + <li> + <b>Novelty:</b> What is new in the programming language? Are there some new takes on old ideas? Is + there something novel? How is the language an improvement compared to existing languages? Does the + language make you think in a new way about programming? + </li> + + <li> + <b>Resources:</b> What resources are behind the programming language? Is it a hobby project? An open + source project? An academic project? Are you open to collaboration? Do you have backing (from industry + or otherwise)? + </li> + + <li> + <b>Feedback:</b> What kind of feedback are you looking for? What other people think? Suggestions for + improvements and related work? Constructive criticism about the design? What it would take for someone + to consider using it? + </li> + + <li> + <b>Reality Check:</b> Try to avoid grandiose or unsubstantiated claims: Do your compiler really + outperform modern state-of-the-art C compilers? Is your type system really more expressive than + Haskell or Idris? Is your language really safer than Ada? + </li> + </ul> + </p> + + <h2>What about Flix?</h2> + + <p>The time has come to nail our colors to the flag:</p> + + <p> + <ul> + <li> + <b>Scope:</b> We are building a real programming language intended for real-world use. It is an + open-source project lead by academic programming language researchers. + </li> + + <li> + <b>Implementation:</b> The Flix compiler project is ~137,000 lines of code. We have a realistic + compiler, a standard library (extensive, but still under development), a Visual Studio Code extension + (with auto-complete!), an online playground, online documentation, and several published papers on the + novel aspects of the language. + </li> + + <li> + <b>Novelty:</b> We have a whole page (<Link to="/innovations/">Innovations</Link>) that covers this, + but briefly: a unique combination of features, combined with first-class Datalog constraints and a + polymorphic effect system. + </li> + + <li> + <b>Resources:</b> We are a group of programming language researchers from Aarhus University and the + University of Waterloo together with a small community of open source contributors. Through our + research we have funding for working on Flix. + </li> + + <li> + <b>Feedback:</b> We want to know what people think about Flix, how we can make Flix better, and what + it would take for someone to consider using it. + </li> + + <li> + <b>Reality Check:</b> We aim to under-promise and over-deliver. We do not promote features before they + exist. Our typical pipeline is: (Research) Idea → Implementation → Documentation → Presentation to the + World. Development is not secret; everything is on GitHub. We just don't promote anything before it is + ready. We have exciting things in the pipeline, but you will have to wait a bit before learning about + them (or spoil yourself by diving into the GitHub issues!) + </li> + </ul> + </p> + + <p>Until next time, happy hacking.</p> + </Col> + </Row> + </Container> + ) + } } export default ProgrammingLanguageDefense diff --git a/src/page/blog/Redundancies.js b/src/page/blog/Redundancies.js index e0e57be..c83482c 100644 --- a/src/page/blog/Redundancies.js +++ b/src/page/blog/Redundancies.js @@ -1,44 +1,39 @@ -import React, {Component} from "react"; -import {Col, Container, Row} from "reactstrap"; -import InlineEditor from "../../util/InlineEditor"; +import React, { Component } from 'react' +import { Col, Container, Row } from 'reactstrap' +import InlineEditor from '../../util/InlineEditor' class Redundancies extends Component { + componentDidMount() { + document.title = 'Flix | Redundancies as Compile-Time Errors' + } - componentDidMount() { - document.title = "Flix | Redundancies as Compile-Time Errors"; - } - - render() { - return ( - <Container style={{"text-align": "justify"}}> - <Row className="mb-3"> - <Col sm={12} md={8}> - - <h1>Redundancies as Compile-Time Errors</h1> - - <p> - Posted February 2020 by <i>Magnus Madsen</i>. - </p> - - <p> - As software developers, we strive to write correct and maintainable code. - Today, I want to share some code where I failed in these two goals. - </p> - - <p> - I will show you real-world code from the Flix compiler and ask you to determine what is - wrong with the code. Then, later, I will argue how programming languages can help avoid the - type of problems you will see. (Note to the reader: The Flix compiler is (currently) written - in Scala, so the code is in Scala, but the lessons learned are applied to the Flix - programming language. I hope that makes sense.) - </p> - - <p> - Let us begin our journey by looking at the following code fragment: - </p> - - <InlineEditor> - {`case Expression.ApplyClo(exp, args, tpe, loc) => + render() { + return ( + <Container style={{ 'text-align': 'justify' }}> + <Row className="mb-3"> + <Col sm={12} md={8}> + <h1>Redundancies as Compile-Time Errors</h1> + + <p> + Posted February 2020 by <i>Magnus Madsen</i>. + </p> + + <p> + As software developers, we strive to write correct and maintainable code. Today, I want to share some code + where I failed in these two goals. + </p> + + <p> + I will show you real-world code from the Flix compiler and ask you to determine what is wrong with the + code. Then, later, I will argue how programming languages can help avoid the type of problems you will + see. (Note to the reader: The Flix compiler is (currently) written in Scala, so the code is in Scala, but + the lessons learned are applied to the Flix programming language. I hope that makes sense.) + </p> + + <p>Let us begin our journey by looking at the following code fragment:</p> + + <InlineEditor> + {`case Expression.ApplyClo(exp, args, tpe, loc) => val e = visitExp(exp) val as = args map visitExp Expression.ApplyClo(e, as, tpe, loc) @@ -55,36 +50,26 @@ case Expression.Binary(op, exp1, exp2, tpe, loc) => val e1 = visitExp(exp1) val e2 = visitExp(exp2) Expression.Binary(op, e1, e2, tpe, loc)`} - </InlineEditor> - - <p> - Do you see any issues? - </p> - - <p> - If not, look again. - </p> - - <p> - Ok, got it? - </p> - - <p> - The code has a subtle bug: In the case for <code>Unary</code> the local - variable <code>e</code> holds the result of the recursion on <code>exp</code>. But by - mistake the reconstruction of <code>Unary</code> uses <code>exp</code> and - not <code>e</code> as intended. The local variable <code>e</code> is unused. Consequently, - the specific transformations applied by <code>visitExp</code> under unary expressions are - silently discarded. This bug was in the Flix compiler for some time before it was - discovered. - </p> - - <p> - Let us continue our journey with the following code fragment: - </p> - - <InlineEditor> - {`case ResolvedAst.Expression.IfThenElse(exp1, exp2, exp3, tvar, evar, loc) => + </InlineEditor> + + <p>Do you see any issues?</p> + + <p>If not, look again.</p> + + <p>Ok, got it?</p> + + <p> + The code has a subtle bug: In the case for <code>Unary</code> the local variable <code>e</code> holds the + result of the recursion on <code>exp</code>. But by mistake the reconstruction of <code>Unary</code> uses{' '} + <code>exp</code> and not <code>e</code> as intended. The local variable <code>e</code> is unused. + Consequently, the specific transformations applied by <code>visitExp</code> under unary expressions are + silently discarded. This bug was in the Flix compiler for some time before it was discovered. + </p> + + <p>Let us continue our journey with the following code fragment:</p> + + <InlineEditor> + {`case ResolvedAst.Expression.IfThenElse(exp1, exp2, exp3, tvar, evar, loc) => for { (tpe1, eff1) <- visitExp(exp1) (tpe2, eff2) <- visitExp(exp2) @@ -93,32 +78,24 @@ case Expression.Binary(op, exp1, exp2, tpe, loc) => resultTyp <- unifyTypM(tvar, tpe2, tpe3, loc) resultEff <- unifyEffM(evar, eff1, eff2, loc) } yield (resultTyp, resultEff)`} - </InlineEditor> + </InlineEditor> - <p> - Do you see any issues? - </p> + <p>Do you see any issues?</p> - <p> - If not, look again. - </p> + <p>If not, look again.</p> - <p> - Ok, got it? - </p> + <p>Ok, got it?</p> - <p> - The code has a similar bug: The local variable <code>eff3</code> is not used, but it - should have been used to compute <code>resultEff</code>. While this bug never made it into - any release of Flix, it did cause a lot of head-scratching. - </p> + <p> + The code has a similar bug: The local variable <code>eff3</code> is not used, but it should have been used + to compute <code>resultEff</code>. While this bug never made it into any release of Flix, it did cause a + lot of head-scratching. + </p> - <p> - Now we are getting the hang of things! What about this code fragment?: - </p> + <p>Now we are getting the hang of things! What about this code fragment?:</p> - <InlineEditor> - {`/** + <InlineEditor> + {`/** * Returns the disjunction of the two effects \`eff1\` and \`eff2\`. */ def mkOr(ef1f: Type, eff2: Type): Type = eff1 match { @@ -130,34 +107,27 @@ def mkOr(ef1f: Type, eff2: Type): Type = eff1 match { case _ => Type.Apply(Type.Apply(Type.Cst(TypeConstructor.Or), eff1), eff2) } }`} - </InlineEditor> - - <p> - Do you see any issues? - </p> - - <p> - I am sure you did. - </p> - - <p> - The bug is the following: The formal parameter to <code>mkOr</code> is - misspelled <code>ef1f</code> instead of <code>eff1</code>. But how does this even compile, - you ask? Well, unfortunately the <code>mkOr</code> function is nested inside another - function that just so happens to have an argument also named <code>eff1</code>! - Damn Murphy and his laws. The intention was for the formal parameters - of <code>mkOr</code> to shadow <code>eff1</code> (and <code>eff2</code>), but because of the - misspelling, <code>ef1f</code> ended up as unused and <code>eff1</code> (a completely - unrelated variable) was used instead. The issue was found during development, but not - before several hours of wasted work. Not that I am bitter or anything... - </p> - - <p> - We are almost at the end of our journey! But what about this beast: - </p> - - <InlineEditor> - {`/** + </InlineEditor> + + <p>Do you see any issues?</p> + + <p>I am sure you did.</p> + + <p> + The bug is the following: The formal parameter to <code>mkOr</code> is misspelled <code>ef1f</code>{' '} + instead of <code>eff1</code>. But how does this even compile, you ask? Well, unfortunately the{' '} + <code>mkOr</code> function is nested inside another function that just so happens to have an argument also + named <code>eff1</code>! Damn Murphy and his laws. The intention was for the formal parameters of{' '} + <code>mkOr</code> to shadow <code>eff1</code> (and <code>eff2</code>), but because of the misspelling,{' '} + <code>ef1f</code> ended up as unused and <code>eff1</code> (a completely unrelated variable) was used + instead. The issue was found during development, but not before several hours of wasted work. Not that I + am bitter or anything... + </p> + + <p>We are almost at the end of our journey! But what about this beast:</p> + + <InlineEditor> + {`/** * Returns the result of looking up the given \`field\` on the given \`klass\`. */ def lookupNativeField(klass: String, field: String, loc: Location): ... = try { @@ -180,141 +150,118 @@ def lookupNativeField(klass: String, field: String, loc: Location): ... = try { case ex: ClassNotFoundException => Err(NameError.UndefinedNativeClass(klass, loc)) }`} - </InlineEditor> - - <p> - Do you see any issues? - </p> - - <p> - If not, look again. - </p> - - <p> - Ok, got it? - </p> - - <p> - Still nothing? - </p> - - <p> - <i>Pause for dramatic effect.</i> - </p> - - <p> - Morpheus: What if I told you... - </p> - - <p> - Morpheus: ... that the function has been maintained over a long period of time... - </p> - - <p> - Morpheus: <i>But that there is no place where the function is called!</i> - </p> - - <p> - I am sorry if that was unfair. But was it really? The Flix code base is more than 100,000 - lines of code, so it is hard to imagine that a single person can hold it in his or her head. - </p> - - <p> - As these examples demonstrate, and as has been demonstrated in the research literature (see - e.g. <a href="https://web.stanford.edu/~engler/p401-xie.pdf">Xie and Engler 2002</a>), - redundant or unused code is often buggy code. - </p> - - <p> - To overcome such issues, Flix is very strict about redundant and unused code. - </p> - - <h5>Flix Treats Unused Code as Compile-Time Errors</h5> - - <p> - The Flix compiler emits a <i>compile-time error</i> for the following redundancies: - </p> - - <p> - <table className="table table-striped small"> - <thead> - <tr> - <th scope="col">Type</th> - <th scope="col">Description</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">Unused Def</th> - <td>A function is declared, but never used.</td> - </tr> - <tr> - <th scope="row">Unused Enum</th> - <td>An enum type is declared, but never used.</td> - </tr> - <tr> - <th scope="row">Unused Enum Case</th> - <td>A case (variant) of an enum is declared, but never used.</td> - </tr> - <tr> - <th scope="row">Unused Formal Parameter</th> - <td>A formal parameter is declared, but never used.</td> - </tr> - <tr> - <th scope="row">Unused Type Parameter</th> - <td>A function or enum declares a type parameter, but it is never used.</td> - </tr> - <tr> - <th scope="row">Unused Local Variable</th> - <td>A function declares a local variable, but it is never used.</td> - </tr> - <tr> - <th scope="row">Shadowed Local Variable</th> - <td>A local variable hides another local variable.</td> - </tr> - <tr> - <th scope="row">Unconditional Recursion</th> - <td>A function unconditionally recurses on all control-flow paths.</td> - </tr> - <tr> - <th scope="row">Useless Expression Statement</th> - <td>An expression statement discards the result of a pure expression.</td> - </tr> - </tbody> - </table> - </p> - - <p> - As the Flix language grows, we will continue to expand the list. - </p> - - <p> - Let us look at three concrete examples of such compile-time errors. - </p> - - <h5>Example I: Unused Local Variable</h5> - - <p> - Given the program fragment: - </p> - - <InlineEditor> - {`def main(): Bool = + </InlineEditor> + + <p>Do you see any issues?</p> + + <p>If not, look again.</p> + + <p>Ok, got it?</p> + + <p>Still nothing?</p> + + <p> + <i>Pause for dramatic effect.</i> + </p> + + <p>Morpheus: What if I told you...</p> + + <p>Morpheus: ... that the function has been maintained over a long period of time...</p> + + <p> + Morpheus: <i>But that there is no place where the function is called!</i> + </p> + + <p> + I am sorry if that was unfair. But was it really? The Flix code base is more than 100,000 lines of code, + so it is hard to imagine that a single person can hold it in his or her head. + </p> + + <p> + As these examples demonstrate, and as has been demonstrated in the research literature (see e.g.{' '} + <a href="https://web.stanford.edu/~engler/p401-xie.pdf">Xie and Engler 2002</a>), redundant or unused code + is often buggy code. + </p> + + <p>To overcome such issues, Flix is very strict about redundant and unused code.</p> + + <h5>Flix Treats Unused Code as Compile-Time Errors</h5> + + <p> + The Flix compiler emits a <i>compile-time error</i> for the following redundancies: + </p> + + <p> + <table className="table table-striped small"> + <thead> + <tr> + <th scope="col">Type</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">Unused Def</th> + <td>A function is declared, but never used.</td> + </tr> + <tr> + <th scope="row">Unused Enum</th> + <td>An enum type is declared, but never used.</td> + </tr> + <tr> + <th scope="row">Unused Enum Case</th> + <td>A case (variant) of an enum is declared, but never used.</td> + </tr> + <tr> + <th scope="row">Unused Formal Parameter</th> + <td>A formal parameter is declared, but never used.</td> + </tr> + <tr> + <th scope="row">Unused Type Parameter</th> + <td>A function or enum declares a type parameter, but it is never used.</td> + </tr> + <tr> + <th scope="row">Unused Local Variable</th> + <td>A function declares a local variable, but it is never used.</td> + </tr> + <tr> + <th scope="row">Shadowed Local Variable</th> + <td>A local variable hides another local variable.</td> + </tr> + <tr> + <th scope="row">Unconditional Recursion</th> + <td>A function unconditionally recurses on all control-flow paths.</td> + </tr> + <tr> + <th scope="row">Useless Expression Statement</th> + <td>An expression statement discards the result of a pure expression.</td> + </tr> + </tbody> + </table> + </p> + + <p>As the Flix language grows, we will continue to expand the list.</p> + + <p>Let us look at three concrete examples of such compile-time errors.</p> + + <h5>Example I: Unused Local Variable</h5> + + <p>Given the program fragment:</p> + + <InlineEditor> + {`def main(): Bool = let l1 = List.range(0, 10); let l2 = List.intersperse(42, l1); let l3 = List.range(0, 10); let l4 = List.map(x -> x :: x :: Nil, l2); let l5 = List.flatten(l4); List.exists(x -> x == 0, l5)`} - </InlineEditor> + </InlineEditor> - <p> - The Flix compiler emits the compile-time error: - </p> + <p>The Flix compiler emits the compile-time error:</p> - - <InlineEditor> - {`-- Redundancy Error -------------------------------------------------- foo.flix + <InlineEditor> + {`-- Redundancy Error -------------------------------------------------- foo.flix >> Unused local variable 'l3'. The variable is not referenced within its scope. @@ -331,38 +278,33 @@ Possible fixes: Compilation failed with 1 error(s).`} - </InlineEditor> + </InlineEditor> - <p> - The error message offers suggestions for how to fix the problem or alternatively how to make - the compiler shut up (by explicitly marking the variable as unused). - </p> + <p> + The error message offers suggestions for how to fix the problem or alternatively how to make the compiler + shut up (by explicitly marking the variable as unused). + </p> - <p> - Modern programming languages like Elm and Rust offer a similar feature. - </p> + <p>Modern programming languages like Elm and Rust offer a similar feature.</p> - <h5>Example II: Unused Enum Case</h5> + <h5>Example II: Unused Enum Case</h5> - <p> - Given the enum declaration: - </p> + <p>Given the enum declaration:</p> - <InlineEditor> - {`enum Color { + <InlineEditor> + {`enum Color { case Red, case Green, case Blue }`} - </InlineEditor> + </InlineEditor> - <p> - If only <code>Red</code> and <code>Green</code> are used then we get the Flix compile-time - error: - </p> + <p> + If only <code>Red</code> and <code>Green</code> are used then we get the Flix compile-time error: + </p> - <InlineEditor> - {`-- Redundancy Error -------------------------------------------------- foo.flix + <InlineEditor> + {`-- Redundancy Error -------------------------------------------------- foo.flix >> Unused case 'Blue' in enum 'Color'. @@ -377,30 +319,24 @@ Possible fixes: (3) Prefix the case with an underscore. Compilation failed with 1 error(s).`} - </InlineEditor> + </InlineEditor> - <p> - Again, programming languages like Elm and Rust offer a similar feature. - </p> + <p>Again, programming languages like Elm and Rust offer a similar feature.</p> - <h5>Example III: Useless Expression Statement</h5> + <h5>Example III: Useless Expression Statement</h5> - <p> - Given the program fragment: - </p> + <p>Given the program fragment:</p> - <InlineEditor> - {`def main(): Int = + <InlineEditor> + {`def main(): Int = List.map(x -> x + 1, 1 :: 2 :: Nil); 123`} - </InlineEditor> + </InlineEditor> - <p> - The Flix compiler emits the compile-time error: - </p> + <p>The Flix compiler emits the compile-time error:</p> - <InlineEditor> - {`-- Redundancy Error -------------------------------------------------- foo.flix + <InlineEditor> + {`-- Redundancy Error -------------------------------------------------- foo.flix >> Useless expression: It has no side-effect(s) and its result is discarded. @@ -416,79 +352,67 @@ Possible fixes: (3) Introduce a let-binding with a wildcard name. Compilation failed with 1 error(s).`} - </InlineEditor> - - - <p> - The problem with the code is that the evaluation of <code>List.map(x -{">"} x + 1, 1 :: 2 :: - Nil)</code> has no side-effect(s) and its result is discarded. - </p> - - <p> - Another classic instance of this problem is when someone calls - e.g. <code>checkPermission(...)</code> and expects it to throw an exception if the user has - insufficient permissions, but in fact, the function simply returns a boolean which is then - discarded. - </p> - - <p> - But this is <i>not</i> your Grandma's average compile-time error. At the time of writing, I - know of no other programming language that offers a similar warning or error with - the same precision as Flix. If you do, please drop me a line on Gitter. (Before someone - rushes to suggest <code>must_use</code> and friends, please consider whether they work in - the presence of polymorphism as outlined below). - </p> - - <p> - The key challenge is to (automatically) determine whether an expression is pure - (side-effect free) in the presence of polymorphism. Specifically, the call - to <code>List.map</code> is pure because the <i>function argument</i> <code>x -{">"} x + - 1</code> is pure. In other words, the purity of <code>List.map</code> depends on the purity - of its argument: it is <i>effect polymorphic</i>. The combination of type inference, - fine-grained effect inference, and effect polymorphism is a strong cocktail that I plan to - cover in a future blog post. - </p> - - <p> - Note: The above is fully implemented in master, but has not yet been "released". - </p> - - <h5>Closing Thoughts</h5> - - <p> - I hope that I have convinced you that unused code is a threat to correct and maintainable - code. However, it is a threat that can be neutralized by better programming language design - and with minor changes to development practices. Moreover, I believe that a compiler that - reports redundant or unused code can help programmers – whether inexperienced or - seasoned – avoid stupid mistakes that waste time during development. - </p> - - <p> - A reasonable concern is whether working with a compiler that rejects programs with unused - code is too cumbersome or annoying. In my experience, the answer is no. After - a small learning period, whenever you want to introduce a new code fragment that will not - immediately be used, you simple remember to prefix it with an underscore, and then later you - come back and remove the underscore when you are ready to use it. - </p> - - <p> - While there might be a short adjustment period, the upside is <i>huge</i>: The compiler - provides an iron-clad guarantee that all my code is used. Moreover, whenever I refactor some - code, I am immediately informed if some code fragment becomes unused. I think such long-term - maintainability concerns are significantly more important than a little bit of extra work - during initial development. - </p> - - <p> - Until next time, happy hacking. - </p> - - </Col> - </Row> - </Container> - ); - } - + </InlineEditor> + + <p> + The problem with the code is that the evaluation of <code>List.map(x -{'>'} x + 1, 1 :: 2 :: Nil)</code>{' '} + has no side-effect(s) and its result is discarded. + </p> + + <p> + Another classic instance of this problem is when someone calls e.g. <code>checkPermission(...)</code> and + expects it to throw an exception if the user has insufficient permissions, but in fact, the function + simply returns a boolean which is then discarded. + </p> + + <p> + But this is <i>not</i> your Grandma's average compile-time error. At the time of writing, I know of no + other programming language that offers a similar warning or error with the same precision as Flix. If you + do, please drop me a line on Gitter. (Before someone rushes to suggest <code>must_use</code> and friends, + please consider whether they work in the presence of polymorphism as outlined below). + </p> + + <p> + The key challenge is to (automatically) determine whether an expression is pure (side-effect free) in the + presence of polymorphism. Specifically, the call to <code>List.map</code> is pure because the{' '} + <i>function argument</i> <code>x -{'>'} x + 1</code> is pure. In other words, the purity of{' '} + <code>List.map</code> depends on the purity of its argument: it is <i>effect polymorphic</i>. The + combination of type inference, fine-grained effect inference, and effect polymorphism is a strong cocktail + that I plan to cover in a future blog post. + </p> + + <p>Note: The above is fully implemented in master, but has not yet been "released".</p> + + <h5>Closing Thoughts</h5> + + <p> + I hope that I have convinced you that unused code is a threat to correct and maintainable code. However, + it is a threat that can be neutralized by better programming language design and with minor changes to + development practices. Moreover, I believe that a compiler that reports redundant or unused code can help + programmers – whether inexperienced or seasoned – avoid stupid mistakes that waste time during + development. + </p> + + <p> + A reasonable concern is whether working with a compiler that rejects programs with unused code is too + cumbersome or annoying. In my experience, the answer is no. After a small learning period, whenever you + want to introduce a new code fragment that will not immediately be used, you simple remember to prefix it + with an underscore, and then later you come back and remove the underscore when you are ready to use it. + </p> + + <p> + While there might be a short adjustment period, the upside is <i>huge</i>: The compiler provides an + iron-clad guarantee that all my code is used. Moreover, whenever I refactor some code, I am immediately + informed if some code fragment becomes unused. I think such long-term maintainability concerns are + significantly more important than a little bit of extra work during initial development. + </p> + + <p>Until next time, happy hacking.</p> + </Col> + </Row> + </Container> + ) + } } export default Redundancies diff --git a/src/page/misc/Checklist.js b/src/page/misc/Checklist.js index f8a0532..078fdfc 100644 --- a/src/page/misc/Checklist.js +++ b/src/page/misc/Checklist.js @@ -1,24 +1,24 @@ -import React, {Component} from 'react'; -import {Container} from "reactstrap"; +import React, { Component } from 'react' +import { Container } from 'reactstrap' class Checklist extends Component { + componentDidMount() { + document.title = 'Flix | Programming Language Checklist' + } - componentDidMount() { - document.title = "Flix | Programming Language Checklist"; - } + render() { + return ( + <Container> + <h1>Programming Language Checklist</h1> - render() { - return ( - <Container> - <h1>Programming Language Checklist</h1> + <p> + For completeness (and fun), here is the{' '} + <a href="http://colinm.org/language_checklist.html">programming language check list</a> for Flix: + </p> - <p> - For completeness (and fun), here is the <a href="http://colinm.org/language_checklist.html">programming - language check list</a> for Flix: - </p> - - <code> - <pre>{`You appear to be advocating a new: + <code> + <pre> + {`You appear to be advocating a new: [x] functional [x] imperative [ ] object-oriented [ ] procedural [ ] stack-based [x] "multi-paradigm" [x] lazy [x] eager [x] statically-typed [ ] dynamically-typed [x] pure [x] impure [ ] non-hygienic [ ] visual [ ] beginner-friendly @@ -119,11 +119,11 @@ In conclusion, this is what I think of you: [ ] This is a bad language, and you should feel bad for inventing it. [ ] Programming in this language is an adequate punishment for inventing it. `} - </pre> - </code> - </Container> - ); - } + </pre> + </code> + </Container> + ) + } } -export default Checklist \ No newline at end of file +export default Checklist diff --git a/src/util/Codebox.js b/src/util/Codebox.js index af3e2dc..f060cd3 100644 --- a/src/util/Codebox.js +++ b/src/util/Codebox.js @@ -1,128 +1,132 @@ -import React, {Component} from "react"; -import SamplesData from "../data/Samples"; -import Editor from "./Editor"; -import { - Button, Col, Container, InputGroup, Row -} from "reactstrap"; -import FontAwesome from 'react-fontawesome'; -import PulseLoader from 'react-spinners/PulseLoader'; +import React, { Component } from 'react' +import SamplesData from '../data/Samples' +import Editor from './Editor' +import { Button, Col, Container, InputGroup, Row } from 'reactstrap' +import FontAwesome from 'react-fontawesome' +import PulseLoader from 'react-spinners/PulseLoader' class Codebox extends Component { - - constructor(props) { - super(props); - let randomChoice = getRandomInt(SamplesData.length); - this.state = { - choice: randomChoice, - samples: SamplesData, - dropdown: false, - input: SamplesData[randomChoice].code, - output: undefined - }; - } - - toggleDropDown() { - this.setState({dropdown: !this.state.dropdown}); + constructor(props) { + super(props) + let randomChoice = getRandomInt(SamplesData.length) + this.state = { + choice: randomChoice, + samples: SamplesData, + dropdown: false, + input: SamplesData[randomChoice].code, + output: undefined, } + } - onDropdownChoice(event) { - let newChoice = Number(event.target.value); - this.setState({ - choice: newChoice, - input: this.state.samples[newChoice].code, - output: undefined - }); - } + toggleDropDown() { + this.setState({ dropdown: !this.state.dropdown }) + } - onTextChanged(input) { - this.setState({input: input}); - } + onDropdownChoice(event) { + let newChoice = Number(event.target.value) + this.setState({ + choice: newChoice, + input: this.state.samples[newChoice].code, + output: undefined, + }) + } - onRunClick = () => { - this.setState({output: null}, () => { - this.props.flix.run(this.state.input, data => - this.setState({output: data}) - ); - }); - }; + onTextChanged(input) { + this.setState({ input: input }) + } - getRunButton() { - let enabled = this.props.flix.connected; - return <Button color="success" onClick={this.onRunClick} size="sm" disabled={!enabled}> - Run <FontAwesome name="play" className="ml-2"/> - </Button>; - } + onRunClick = () => { + this.setState({ output: null }, () => { + this.props.flix.run(this.state.input, data => this.setState({ output: data })) + }) + } - getDropDown() { - return <select - value={this.state.choice} - onChange={this.onDropdownChoice.bind(this)} - style={{"textOverflow": "ellipsis"}} - className="ml-2 w-75"> - {this.state.samples.map((sample, index) => - <option key={index} value={index}>{sample.name}</option>) - } - </select> - } + getRunButton() { + let enabled = this.props.flix.connected + return ( + <Button color="success" onClick={this.onRunClick} size="sm" disabled={!enabled}> + Run <FontAwesome name="play" className="ml-2" /> + </Button> + ) + } - getNameOfSelection() { - return this.state.samples[this.state.choice].name; - } + getDropDown() { + return ( + <select + value={this.state.choice} + onChange={this.onDropdownChoice.bind(this)} + style={{ textOverflow: 'ellipsis' }} + className="ml-2 w-75" + > + {this.state.samples.map((sample, index) => ( + <option key={index} value={index}> + {sample.name} + </option> + ))} + </select> + ) + } - getEditor() { - return <Editor key={this.state.input.leading} - code={this.state.input} - notifyTextChanged={this.onTextChanged.bind(this)}/> - } + getNameOfSelection() { + return this.state.samples[this.state.choice].name + } - getOutput() { - if (this.state.output === undefined) { - return undefined; - } else if (this.state.output === null) { - return <Row> - <Col md="12" className="text-center"> - <PulseLoader - size={16} - sizeUnit={"px"} - color={'#28a745'} - loading={true} - className="loader" - /> - </Col> - </Row> - } else { - if (this.state.output.status === "success") { - return ( - <Container className="mt-3 editor-output"> - <h5>Standard Output</h5> - <pre>{this.state.output.result}</pre> - </Container>); - } else { - return ( - <Container className="mt-3 editor-output"> - <h5>Standard Output</h5> - <pre>{this.state.output.result}</pre> - </Container>); - } - } - } + getEditor() { + return ( + <Editor + key={this.state.input.leading} + code={this.state.input} + notifyTextChanged={this.onTextChanged.bind(this)} + /> + ) + } - render() { + getOutput() { + if (this.state.output === undefined) { + return undefined + } else if (this.state.output === null) { + return ( + <Row> + <Col md="12" className="text-center"> + <PulseLoader size={16} sizeUnit={'px'} color={'#28a745'} loading={true} className="loader" /> + </Col> + </Row> + ) + } else { + if (this.state.output.status === 'success') { + return ( + <Container className="mt-3 editor-output"> + <h5>Standard Output</h5> + <pre>{this.state.output.result}</pre> + </Container> + ) + } else { return ( - <div> - <InputGroup className="mt-2 mb-3"> - {this.getRunButton()} - {this.getDropDown()} - </InputGroup> - {this.getEditor()} - {this.getOutput()} - </div> - ); + <Container className="mt-3 editor-output"> + <h5>Standard Output</h5> + <pre>{this.state.output.result}</pre> + </Container> + ) + } } + } + + render() { + return ( + <div> + <InputGroup className="mt-2 mb-3"> + {this.getRunButton()} + {this.getDropDown()} + </InputGroup> + {this.getEditor()} + {this.getOutput()} + </div> + ) + } } function getRandomInt(max) { - return Math.floor(Math.random() * Math.floor(max)); + return Math.floor(Math.random() * Math.floor(max)) } -export default Codebox; +export default Codebox diff --git a/src/util/Editor.js b/src/util/Editor.js index fd8816a..21e729e 100644 --- a/src/util/Editor.js +++ b/src/util/Editor.js @@ -1,36 +1,38 @@ -import React, {Component} from 'react'; +import React, { Component } from 'react' import AceEditor from 'react-ace' import 'brace/mode/scala' import FlixMode from './FlixMode' -import 'brace/theme/chrome'; +import 'brace/theme/chrome' class Editor extends Component { - componentDidMount() { - let customMode = new FlixMode(); - this.refs.aceEditor.editor.getSession().setMode(customMode); - } + componentDidMount() { + let customMode = new FlixMode() + this.refs.aceEditor.editor.getSession().setMode(customMode) + } - onChange(input) { - this.props.notifyTextChanged(input) - }; + onChange(input) { + this.props.notifyTextChanged(input) + } - render() { - return ( - <AceEditor width="100%" - mode='text' - theme='chrome' - ref="aceEditor" - showGutter={false} - showPrintMargin={false} - highlightActiveLine={false} - onChange={this.onChange.bind(this)} - value={this.props.code} - autoScrollEditorIntoView={true} - maxLines={25} - editorProps={{$blockScrolling: true}}/> - ) - } + render() { + return ( + <AceEditor + width="100%" + mode="text" + theme="chrome" + ref="aceEditor" + showGutter={false} + showPrintMargin={false} + highlightActiveLine={false} + onChange={this.onChange.bind(this)} + value={this.props.code} + autoScrollEditorIntoView={true} + maxLines={25} + editorProps={{ $blockScrolling: true }} + /> + ) + } } export default Editor diff --git a/src/util/FlixMode.js b/src/util/FlixMode.js index 7d0ec39..92e983d 100644 --- a/src/util/FlixMode.js +++ b/src/util/FlixMode.js @@ -1,77 +1,86 @@ -import 'brace/mode/java'; +import 'brace/mode/java' -export class CustomHighlightRules extends window.ace.acequire("ace/mode/text_highlight_rules").TextHighlightRules { - constructor() { - super(); +export class CustomHighlightRules extends window.ace.acequire('ace/mode/text_highlight_rules').TextHighlightRules { + constructor() { + super() - var keywords = ( - "namespace|def|case|enum|opaque|type|alias|rel|lat|use|null|ref|deref|if|else|let|let*|new|as|get|set|import|match|match?|select|spawn|???|solve|project|fold|query|instance|class|with|from|into|static" - ); + var keywords = + 'namespace|def|case|enum|opaque|type|alias|rel|lat|use|null|ref|deref|if|else|let|let*|new|as|get|set|import|match|match?|select|spawn|???|solve|project|fold|query|instance|class|with|from|into|static' - var builtinConstants = ( - "true|false|Nil" - ); + var builtinConstants = 'true|false|Nil' - var builtinFunctions = ( - "avg" - ); + var builtinFunctions = 'avg' - var dataTypes = ( - "Unit|Bool|Char|Float32|Float64|Int|Int8|Int16|Int32|Int64|BigInt|String|Array|Channel|Ref|true|false|not|and|or|Pure|Impure" - ); + var dataTypes = + 'Unit|Bool|Char|Float32|Float64|Int|Int8|Int16|Int32|Int64|BigInt|String|Array|Channel|Ref|true|false|not|and|or|Pure|Impure' - var keywordMapper = this.createKeywordMapper({ - "support.function": builtinFunctions, - "keyword": keywords, - "constant.language": builtinConstants, - "storage.type": dataTypes - }, "identifier", true); + var keywordMapper = this.createKeywordMapper( + { + 'support.function': builtinFunctions, + keyword: keywords, + 'constant.language': builtinConstants, + 'storage.type': dataTypes, + }, + 'identifier', + true, + ) - this.$rules = { - "start" : [ { - token : "comment", - regex : "\\/\\/.*$" - }, { - token : "comment", - start : "/\\*", - end : "\\*/" - }, { - token : "string", // " string - regex : '".*?"' - }, { - token : "string", // ' string - regex : "'.*?'" - }, { - token : "string", // ` string (apache drill) - regex : "`.*?`" - }, { - token : "constant.numeric", // float - regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" - }, { - token : keywordMapper, - regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" - }, { - token : "keyword.operator", - regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|=" - }, { - token : "paren.lparen", - regex : "[\\(]" - }, { - token : "paren.rparen", - regex : "[\\)]" - }, { - token : "text", - regex : "\\s+" - } ] - }; - this.normalizeRules(); + this.$rules = { + start: [ + { + token: 'comment', + regex: '\\/\\/.*$', + }, + { + token: 'comment', + start: '/\\*', + end: '\\*/', + }, + { + token: 'string', // " string + regex: '".*?"', + }, + { + token: 'string', // ' string + regex: "'.*?'", + }, + { + token: 'string', // ` string (apache drill) + regex: '`.*?`', + }, + { + token: 'constant.numeric', // float + regex: '[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b', + }, + { + token: keywordMapper, + regex: '[a-zA-Z_$][a-zA-Z0-9_$]*\\b', + }, + { + token: 'keyword.operator', + regex: '\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|=', + }, + { + token: 'paren.lparen', + regex: '[\\(]', + }, + { + token: 'paren.rparen', + regex: '[\\)]', + }, + { + token: 'text', + regex: '\\s+', + }, + ], } + this.normalizeRules() + } } export default class FlixMode extends window.ace.acequire('ace/mode/java').Mode { - constructor() { - super(); - this.HighlightRules = CustomHighlightRules; - } + constructor() { + super() + this.HighlightRules = CustomHighlightRules + } } - diff --git a/src/util/InlineEditor.js b/src/util/InlineEditor.js index c067512..40328ce 100644 --- a/src/util/InlineEditor.js +++ b/src/util/InlineEditor.js @@ -1,50 +1,51 @@ -import React, {Component} from 'react'; +import React, { Component } from 'react' import AceEditor from 'react-ace' import 'brace/mode/scala' import FlixMode from './FlixMode' -import 'brace/theme/chrome'; +import 'brace/theme/chrome' class InlineEditor extends Component { - constructor(props) { - super(props); - this.state = this.getInitialState(); - } + constructor(props) { + super(props) + this.state = this.getInitialState() + } - getInitialState() { - return { - input: this.props.children - } + getInitialState() { + return { + input: this.props.children, } + } - componentDidMount() { - const customMode = new FlixMode(); - this.refs.aceEditor.editor.getSession().setMode(customMode); - } + componentDidMount() { + const customMode = new FlixMode() + this.refs.aceEditor.editor.getSession().setMode(customMode) + } - render() { - return ( - <div className="inline-editor-frame"> - <div className="inline-editor-code"> - <AceEditor - style={{"background": "inherit", "width": "95%"}} - mode='text' - theme='chrome' - ref="aceEditor" - readOnly={true} - showGutter={false} - showPrintMargin={false} - highlightActiveLine={false} - onChange={this.onChange} - value={this.state.input} - autoScrollEditorIntoView={true} - minLines={1} - maxLines={40} - editorProps={{$blockScrolling: true}}/> - </div> - </div> - ) - } + render() { + return ( + <div className="inline-editor-frame"> + <div className="inline-editor-code"> + <AceEditor + style={{ background: 'inherit', width: '95%' }} + mode="text" + theme="chrome" + ref="aceEditor" + readOnly={true} + showGutter={false} + showPrintMargin={false} + highlightActiveLine={false} + onChange={this.onChange} + value={this.state.input} + autoScrollEditorIntoView={true} + minLines={1} + maxLines={40} + editorProps={{ $blockScrolling: true }} + /> + </div> + </div> + ) + } } -export default InlineEditor \ No newline at end of file +export default InlineEditor