News for hackers. Stuff that matters.

yiransheng

Re:Was BASIC that horrible or better? on Saturday December 23, 2023 @06:57AM (#38743573)
Trying to compile Basic is actually a bit trickier than just implementing an interpreter indeed. Like the FOR statement example you mentioned. Another messy situation is non-lexical FOR/NEXT like here [1], where NEXT can be encountered before a FOR statement, fairly certain I did not get it entirely right there.

Original Dartmouth BASIC had only 14 statement types, and it takes very little efforts to enumerate and implement all of them, even if you are just starting on a compiler journey and making things up suboptimally along the way.

The bonus upside for choosing BASIC as your first compiler project is that you get decades of vintage test programs to play with like this one [2].

[1] https://github.com/yiransheng/basic_rs/blob/ddd64e2eacfc2b36...

[2] Game of Life compiled to warm: http://subdued-afternoon.surge.sh/

Re:How can some infinities be bigger than others? on Wednesday April 19, 2023 @07:26PM (#35634576)
What you described is called Continuum hypothesis[1]. Surprisingly it cannot be proven to be either true or false from(is independent of) ZFC set theory.

[1] https://en.m.wikipedia.org/wiki/Continuum_hypothesis

Re:Rayo's Number on Sunday October 27, 2019 @09:24AM (#21369532)
This number is the result of a "large number duel"[1] between MIT Associate Professor Agustin Rayo (The Mexican Multiplier) and Princeton Associate Professor Adam N. Elga (Dr. Evil)[2]. Possible the world record largest number by some standards.

[1] https://www.scottaaronson.com/writings/bignumbers.html

[2] http://tech.mit.edu/V126/N64/64largenumber.html

Re:The unlikely resurgence of Dungeons and Dragons on Wednesday January 09, 2019 @03:11AM (#18863145)
I would recommend check out urealms[1]. It is a improv/role playing show running on rules similar (but simplifed) DnD rules. The format is a group of twitch personalities steam their gameplay for a live audience, contents including improv jokes, pre-planned dramma, pre-made animation cut scences and at the center of it, dice-roll based table top game play.

The primary tool used for the show is tabletop simulator[2], which is a game designed for any tabletop games: cards, dices, chess etc. and can be customized quite a bit. It's mostly a low-tech solution, replicating physical acts of throwing dices, moving pieces and shuffling cards on a virtual table. In addition, the creators of URealm also invested in other custom softwares and artwork. However, the show is a for-profit project seeks to provide entertainment value for an audience rather than purely for the enjoyment of participants.

[1] https://www.urealms.com/ [2] https://store.steampowered.com/app/286160/Tabletop_Simulator...

Re:Bytecode compilers and interpreters on Friday January 04, 2019 @05:11AM (#18822977)
Oh nice. I have been writing a BASIC bytecode interpreter (and a compiler for WebAssembly)[1] in Rust.

It's a bit slower to get rolling than Python - especially function value representation and dynamic dispatch, unlike Python, could not just make a callable object on the fly. Handling function/procedure calls in a stack VM is definitely a fun exercise, and there seems to be many ways to skin the cat. Shared vs. dedicated data stack across functions, adding registers (unlimited number if required) etc.

[1] https://github.com/yiransheng/basic_rs

Re:Why Do React Hooks Rely on Call Order? on Thursday December 13, 2018 @07:25AM (#18671802)
Hooks reminds me of tensorflow scopes a little bit, in python:

    with tf.variable_scope("foo"):
        with tf.variable_scope("bar"):
            v = tf.get_variable("v", [1])
            assert v.name == "foo/bar/v:0"

`v` tensor here will have a generated human readable unique name here: "foo/bar/v:0"

It seems with hooks, react uses call order to derive the unique "leaf" hook id for runtime resolving its implementations. However, it would be nice if react hooks can automatically provide a similar human readable "hook id" (even if only for dev/debug build).

    function useWindowWidth() {
      const [[width, setWidth], stateId] = debug(useState);

      assert(stateId === "useWindowWidth/state/:0");

      useEffect(() => { ... });
      const [_, effId] = debug(useEffect, () => { ... });

      assert(effId === 'useWindowWidth/effect/:1");

      return width;
    }
This will definitely help for nested custom hooks..
Re:When Functional Programming Isn't Functional on Monday April 02, 2018 @04:00AM (#16733050)
In this case, I think Java's lack of tuples adds quite a bit of syntactic noise, a similar version in rust (another language with method chaining based iterators):

    let generated: Vec<i32> = 
        itertools::iterate((0, 1), |&(a, b)| (b, a + b))
            .map(|s| s.0)
            .take(10)
            .collect();

Arguably, this is closer to the matrix form of Fibonacci series[1]. In addition, the same code structure can generalize to any series with a recursive definition in the form of: a_n = f(a_{n-1}, a_{n-2}, ..., a_{n-k}) - which by some standard expresses intent better. Especially, for some k, the mental overhead of a loop version is too much to bare :)

[1] https://wikimedia.org/api/rest_v1/media/math/render/svg/c795...

Re:How fast is AMP really? on Monday April 02, 2018 @03:27AM (#16732940)
Really impressed! Took a quick look at page source, a couple of observations on why it's fast:

1. Plain, small html - page size is 6.1 kb (request took 700ms for me, I guess the server side rendering is pretty fast too), css file 11kb; note html, css and js are all properly minified

2. Font-awesome and jquery at the bottom of page to not block page rendering, both loaded throught cdn (although a fallback jQuery exists)

3. Site's own js is only 5.6k

4. No large static assets, only image on page is an svg dlogo

5. Did not check with js off, but saw hints of decent fallbacks for no-script

Re:Why we rewrote Lua in JS (2017) on Monday April 02, 2018 @03:13AM (#16732881)
The list of niceties of lua from the article:

> First class functions and closures

> A versatile data structure: the table

> Vararg expressions

> Lexical scoping

> Iterators

> Coroutines (see below)

Well, looking at modern day js:

* First class functions and closures, check

* the table: a combination of `Array`, `Map` and `Map<Number, T>` can prettify much cover typical usecases of lua tables, so js is close in this regard

* Vararg expressions, check

* Lexical scoping, check

* Iterators, check

* Coroutines, with libraries and abstractions on top of generator functions

In addition, in js land, other paradigms of concurrency exists, such as CSP (goroutines), FRP (Rxjs and co). Of course, these can be implemented in Lua as well, but the libraries may not quite as battle-tested.

The author also mentions a sane coercion system; this still true, but ever since "use strict", unexpected coercions can mostly be avoided in js.

On the other hand, js has:

1. Typescript and static typing (a bit unfair to consider this js, but ts gets access to a large portion of high quality npm packages), flow is also great

2. Multiple mature echosystems of UI frameworks (React) - for instance if you need a date picker or an autocompleter, it's just `yarn add` away; I doubt enough such libraries exist for browser side lua yet

3. Tooling support - webpack, prettier, postcss and so on

I like lua, but I feel it does not offer much in addition to what modern js already provides. Of course bring more languages to the browser is always a good thing, on the other hand I do feel this is a tough sell to the larger community.

Re:Update on Async Rendering on Tuesday March 27, 2018 @11:06PM (#16694920)
Interesting mention of create-subscription[1], first time I have heard of such a library/api. Seems it's part of official react repo. Looks like a great piece of utility for interfacing rxjs/xstream etc. Observables. I guess this may replace recompose[2]'s Observable utilities as it's officially endorsed by react team.

Current react ecosystem broadly speakings splits on state management solutions in two styles: 1. Single Observable-like source of truth (redux store) 2. Multi-Observables (relay, appolo, mobx)

It will be interesting to see if `create-subscription` catches on, and whether library authors will start exporting subscriptions as public apis.

[1] https://www.npmjs.com/package/create-subscription

[2] https://github.com/acdlite/recompose/blob/master/docs/API.md...

Re:D3.js 5.0 is out on Thursday March 22, 2018 @07:57PM (#16653853)
Finally, `d3.create`[1] - it has been a minor pain pointer in d3 to create a detached selection for quite some time :)

[1] https://github.com/d3/d3-selection/blob/master/README.md#cre...

Re:Using Prettier to format your JavaScript code on Friday March 09, 2018 @01:50AM (#16550183)
Prettier is such an awesome tool! The best part of it is formatting jsx code - being a mixture of xml and js code, formatting it manually is such a pain. Incidentally, the existence of prettier is also a major reason React stack is my goto choice in Ui works - although it seems prettier support for Vue is [coming](https://github.com/prettier/prettier/issues/2097)
Re:How to Study Mathematics (2017) on Friday February 16, 2018 @08:24PM (#16398256)
Some personal thoughts: the key for me at least, is a bit like the hammer-nail mentality. An software engineer for example has a (small) mathematical toolkit (a hammer), sometimes forcing your problem at hand into the shape of nail is sufficient to solve it.

A dump example, consider the problem of detect if two date ranges overlap (for a calendar app perhaps). By recognizing a date range, DateRange(a, b) as an interval on the real line: [a, b] or a set {x | a <= x <= b}, the problem becomes find if two sets' intersection is empty. Set {x | a <= x <=b } and {x | c <= x <= d}'s intersection is {x | (x >= a and x >= c) and (x <= b and x<=d)} which simplifies to {x | max(a, c) <= x <= min(b, d) }. Therefore, the set is empty iff max(a, c) > min(b, d).

Translating the problem into mathematical structures here (intervals), and manipulate them with math tools (inequalities) would count as applied math I guess. By having a repository of math knowledge and an eager attitude to look for opportunities to apply them, one can find success in solving practical problems. In this context, rigor and formal proofs are less important and math intuition is paramount.

An real world example I like to motivate myself with is Richard Feynman and connection machine[1], a story about Feynman using partial differential equations to model on boolean circuits. I do believe even with a limited set of mathematical tools, by trying them on every problem you encounter, you can still get good results. Something like, if one squint hard enough, you can find a monad anywhere :)

[1] http://longnow.org/essays/richard-feynman-connection-machine...

Re:Kotlin: The Problem with null on Friday January 12, 2018 @08:01PM (#16137628)
In languages like Haskell and Scala that supports `do` / `for` comprehension sugar, this could be done without the nesting:

  fn :: Maybe Int -> Maybe Int -> Int
  fn q z = fromMaybe 0 $
    do 
      q_in <- q
      z_in <- z
      return (q_in + z_in)
Re:Global Mutable State on Tuesday September 19, 2017 @05:44PM (#15289088)
In FP world, there's a somewhat advanced solution to this, Free Monad DSL/Interpreter pattern. I first found out about it in this talk: [https://www.youtube.com/watch?v=fU8eKoakd6o](https://www.you.... There's an example of a pure functional game ai DSL in it.

The gist of the idea is you would write _pure_ functions like this with an imperative style (example in Haskell)

    bullet = do
      player <- getEntityByID playerID
      applyDamage 20 player
This will require some syntactic sugar (do notation in Haskell, for comprehension in Scala) to make it look procedure / imperative. However, the whole expression remains pure, and does not read or write to global state, it's just a data structure capable of expressing steps of mutations (and/or side effects).

A separate part of the system (interpreter) will actually collect all such data structures and apply actual updates to global states in one place and in a principled way.

Some additional benefits includes easily implementing different interpreters (eg. for unit testing), adding "middlewares" to support things like logging and type safety on mutations.

I have no idea whether game programmers uses this pattern or not. However, it's very common in games to add a scripting language (LUA is a popular one) to express things like unit AI, dialog trees on top the underlying engine; which seems rather similar architecturally: adding a layer of indirection, use a expressive (just enough) DSL to encode the logic for mutations with only limited exposure to underlying global states.

A better resource that explores this idea can be found here: http://gameprogrammingpatterns.com/bytecode.html

Re:Leaving Python for JavaScript on Friday August 25, 2017 @01:42PM (#15100546)
ES6+ javaScript in absorbed many great features from python: destructuring vs. tuple unpacking, spread (...) vs *args argument unpacking and generators. Many things I enjoyed in python are now also idiomatic javaScript. Only thing missing is function decorators:

    @connect(...)
    function StateLessComponent(props) {

    }
Re:Chris Lattner on the Realm WWDC 2017 Swift Panel on Saturday July 01, 2017 @02:07AM (#14675650)
Inheritance based OOP models tree-like entites well, where hirachy is defined and clear cut. Unfortunately, lots of real life domains are best expressed by graphs - commonly a DAG. You need to pay attention to your edges and not just the nodes. Inheritance based OOP gives you one keyword to express your edges: extend, and it's horribly inadequate. Mutatable state is not a issue in Java OOP, lacking the expressive power is.
Re:NYPD is canceling its Palantir contract on Saturday July 01, 2017 @01:57AM (#14675626)
Also plottable, one of the few large typescript open source libraries you can depend upon.
With algebraic data type like in Haskell, the state could be typed like this:

    data State a = 
      Loading
      | Failed
      | Loaded [a]
Compared to a representation like `{ loading:true, error: false, pics:[] }`, the above model has the benefit of "making illegal state not representable".

One library in js I like to use to model this type of tagged union / ADT values is single-key[1]. Each variant in a tagged union type is represented by an plain object with just one key, for example:

    const state1 = { Loading: null };
    const state2 = { Failed : <reason> };
    const state3 = { Loaded : [...pics] };

The library offers pattern matching syntax on top of this data representation:

    // render
    const reactElement = match(state, {
      Loading : () => <Loading />,
      Failed  : (reason) => <Error {...reason}/>,
      Loaded  : (pics) => <PicsList pics={pics} />
    });

    // reducer
    const reducer = (state, action) => match(state, {
        Loading : () => {
          switch (action.type) {
            case PICS_FAILURE:
              return { Failure: action.payload };
            case PICS_SUCCESS:
              return { Loaded : action.payload };
            default:
              return state
          }
        },
        Failed : () => {
          switch (action.type) {
            case PICS_REQUEST:
              return { Loading: true };
            default:
              return state;
          }
        },
        Loaded : () => {
          switch (action.type) {
            case PICS_REQUEST:
              return { Loading: true };
            default:
              return state;
          }
        }
      });

    
[1] https://www.npmjs.com/package/single-key
Re:Why Elm? [pdf] on Monday May 08, 2017 @04:52PM (#14295496)
Calmm-js is one of these: https://github.com/calmm-js

Older »