Lisplog

Blogging in Lisp

Search

Feed Aggregator Page 316

Rendered on Mon, 11 Feb 2019 23:31:36 GMT  newer latest older 

Benchmarking overhead of bytes bounds checks

via Elm Discourse - Latest posts by @folkertdev Folkert De Vries on Mon, 11 Feb 2019 23:16:17 GMT

This relates to elm/bytes issue 9: Decoder suppresses stack overflow.

Currently, any error thrown in a bytes decoder is caught and makes the decoder return Nothing.
The reason is that a read (for say a 32-bit integer) can try to read bytes that are out of bounds.
But, exceptions caused by infinite recursion or Debug.todo are also caught and turned into Nothing.

When a byte out of bounds is accessed, a RangeError is thrown. The problem is that infinite recursion (i.e. a stack overflow) will also throw a RangeError, which makes it hard to distinguish these two cases.

But ideally, a Decoder would only result in Nothing when it does out-of-bounds access.
If that were the case you are immediately alerted of infinite recursion or a Debug.todo in a decoder, and when the decoder results in Nothing you know what to look for (too many bytes are read).

I see two options:

  • more fine-grained try/catch such that the only caught exceptions must be out-of-bounds access
  • bounds checks on the buffer before access

In both cases the rest of the code is not in a try/catch block so if exceptions occur they will bubble up.

Benchmark

Evan points out in the issue that the bounds check might be expensive. So I made a benchmark (https://jsperf.com/bytes-bounds-check) and the results are confusing:

In Chrome (72.0.3626)

  • the bounds check is expensive (~ 90% slower)
  • a try/catch has no effect on performance when no exception occurs (why is it faster than the baseline though?)

In Firefox (64.0.0)

  • FF is 10 times slower than Chrome on the baseline
  • a try/catch still has no effect on performance when no exception occurs

Conclusions

I’m suspicious of the benchmark. Is the Firefox implementation of ArrayBuffer really 10 times slower?
In any case there is no performance hit for a try/catch that doesn’t catch an exception, so that solution would work either way for the tested browsers and versions.

Open questions from my side:

  • are the test cases correct, maybe they are optimized in a way that the elm/bytes code could not be?
  • What is wrong with Firefox?
  • I tested this with recent(ish) chrome and firefox on linux. Maybe older/other browsers give different numbers?

Support for HTML in Elm-reactor markdown

via Elm Discourse - Latest posts by @pdamoc Peter Damoc on Mon, 11 Feb 2019 21:07:09 GMT

You could fork the compiler, change the line yourself, build it and use it for that specific case that you have.

For small use cases like this I don’t see any problem.

Package for Drag and Drop for sortable lists with mouse events

via Elm Discourse - Latest posts by @annaghi Anna Bansaghi on Mon, 11 Feb 2019 15:03:25 GMT

Demos, examples and further links are here: annaghi.github.io/dnd-list

  • it does NOT use the native HTML5 Drag and Drop API
  • it relies on the mouse events from the Browser.Events
  • it does NOT handle pointer nor touch events
  • it allows you to style the dragged and the droppable zone elements in your view functions
  • it reorders the list when necessary

This package was inspired by

  • ir4y/elm-dnd
  • zwilias/elm-reorderable
  • Dart Drag and Drop

Support for HTML in Elm-reactor markdown

via Elm Discourse - Latest posts by @jgrenat Jordane Grenat on Mon, 11 Feb 2019 13:12:52 GMT

Hello folks,

I’ve created two years age a 3h-long workshop to teach Elm 0.18 and I’m updating it to be in 0.19. This is currently in french, but I’ll be happy to share it when the translation will be done (really soon as I need it to be ready for Devoxx UK :slight_smile: )

One thing I relied heavily in 0.18 is elm-reactor, as it allows students to have a running dev environment really quickly without needing to install anything else than Elm. For example, I don’t want to presume they already have node installed or anything else.

The instructions for each step of the workshop are in README files, and it’s really convenient because elm-reactor displays them nicely. However, since 0.19, the HTML in markdown is sanitized. It was really convenient though to have well-sized images and to have a little bit more display options.

This is due to the new version of the markdown packages that now sanitizes it by default. Would it be possible to deactivate sanitization for elm-reactor?

Here is the line that would need to be changed: https://github.com/elm/compiler/blob/master/reactor/src/Index/Skeleton.elm#L37

Happy to hear about your opinion on this :slight_smile:

Easy UX suggestions for package.elm-lang.org

via Elm Discourse - Latest posts by @system system on Mon, 11 Feb 2019 08:29:00 GMT

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.

Command, Don’t Query

via The Oozou Blog - Medium by Alireza Bashiri on Mon, 11 Feb 2019 03:55:43 GMT

Have you ever come across chunks of code as below?

An Ruby-ized version of The Art of Enbugging’s example
An enhanced version of Ben Orenstein’s example

That’s a violation of “Tell, Don’t Ask” principle or as I say “Command, Don’t Query”. Which originally has been pointed up by Alec Sharp in Smalltalk By Example book and coined by Andy Hunt and Dave Thomas on their paper The Art of Enbugging.

Procedural code gets information then makes decisions. Object-oriented code tells objects to do things.
— Alec Sharp

How can we embrace “Tell, Don’t Ask”?

When writing code avoid asking questions about an object’s internal state as much as possible due to Object-Oriented principles objects must talk to each other using messages or in this topic commands through a consistent interface.

Command!

Now we’re commanding the object what it should do we’re not trying to be nice or anything ’cause we only care about the outcome instead of asking politely for its states then it’ll give rooms for the object excuses about the other objects information in the future which is also violation of another principle called “Law of Demeter” imagine if in the first example the front panel object interface changes?!

Violation of Law of Demeter

When we can violate “Tell, Don’t Ask”?

In the second example we move the business logic of charging a subscription to subscription object

😈 Hmm, seems okay?! knock knock who’s there? SRP
Now SRP feel at home 😊

The code seems okay but now that we embraced “Tell, Don’t Ask” we actually violated “Single Responsibility Principle” ’cause a subscription shouldn’t charge itself right?! :D So in this case “Single Responsibility Principle” priority is much higher than “Tell, Don’t Ask” so you can easily escape violating it.

Resources to Get You Started

// Tell, Don't Ask
https://pragprog.com/articles/tell-dont-ask

https://martinfowler.com/bliki/TellDontAsk.html
// Law of Demeter
http://wiki.c2.com/?LawOfDemeter

http://wiki.c2.com/?LawOfDemeterIsHardToUnderstand
// SOLID
https://thoughtbot.com/blog/back-to-basics-solid

Thanks for reading and hope you’ve enjoyed your time.


Command, Don’t Query was originally published in The Oozou Blog on Medium, where people are continuing the conversation by highlighting and responding to this story.

Port Support! Let's collaborate on better experiences with ports

via Elm Discourse - Latest posts by @jc00ke Jesse Cooke on Sun, 10 Feb 2019 16:43:00 GMT

Do you know of a good example Elm package that interfaces directly with a library’s API? In my case, there are no real docs on the libraries API (it’s a lot like Stripe Checkout, where you only get a few callbacks to hook into.)

Cannot install any elm packages

via Elm Discourse - Latest posts by @LesleyLai Lesley Lai on Sun, 10 Feb 2019 04:41:56 GMT

Solved:

  1. ping package.elm-lang.org
  2. Adds the ip into /etc/hosts

Correct Asset Paths for Server Side Rendering vs Static File Serving

via Elm Discourse - Latest posts by @stevensonmt Stevensonmt on Sat, 09 Feb 2019 23:34:47 GMT

My app directory structure is something like this:

root/
    main.rs -- where my server runs
    templates.rs -- where the server side rendering templates are called from, including template that calls /elm.js (this path works b/c I am serving the elm/ directory itself as well)
    elm/
         elm.js
         index.html -- static file that calls elm.js
        src/
            Main.elm -- path to image assets is "src/Icons/<specific image file>"
            images/ -- all my icons and other image assets

When I serve the static index.html file the image assets are loaded appropriately. However, when I load elm.js from one of my server side rendered templates, the image assets are not found. I have tried moving the assets folder to root/src/images thinking that would be the equivalent relative path to main.rs as the current path is to index.html, but that does not seem to work. Where should these assets be for the javascript file to find them when it is called from a server side template?

Limitation/Flaw of TEA ... is there a fix?

via Elm Discourse - Latest posts by @system system on Sat, 09 Feb 2019 21:42:40 GMT

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.

Clarify SPA definition for me please

via Elm Discourse - Latest posts by @system system on Sat, 09 Feb 2019 19:29:18 GMT

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.

Running tests for elm/core

via Elm Discourse - Latest posts by @jerith Matt McHenry on Sat, 09 Feb 2019 19:04:38 GMT

TypeError accessing port

via Elm Discourse - Latest posts by @paulh Paul Hollyer on Sat, 09 Feb 2019 10:51:48 GMT

Yes you are right, thank you.

I guess I was jumping ahead with the JS side thinking just defining the port functions in Elm was enough. I’ve moved the call to cache into update and all is good again.

Thanks for the reminder - I won’t forget that again.

TypeError accessing port

via Elm Discourse - Latest posts by @Atlewee Atle Wee Førre on Sat, 09 Feb 2019 10:23:06 GMT

Unused ports is considered dead code and is eliminated in Elm 0.19

Could that be what you are seeing?

Elm Town 41 – Confetti and Waterfalls

via Elm Discourse - Latest posts by @system system on Sat, 09 Feb 2019 10:22:35 GMT

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.

TypeError accessing port

via Elm Discourse - Latest posts by @paulh Paul Hollyer on Sat, 09 Feb 2019 10:13:38 GMT

Hi,

I’m starting a new elm project (0.19) and am having a problem setting up ports out to JS. I have other projects that use ports fine, so this is driving me a little crazy… although it’s my first time using Browser.application so maybe I’m missing something.

I’ve stripped out Main.elm to be just a port module using the simple counter example - which compiles and functions as it should.

However, when I try and reference a port method on the JS side, I get:

TypeError: undefined is not an object (app.ports.cache)

If I change init from

init : Value -> Url -> Nav.Key -> ( Model, Cmd Msg )
init flags url navKey =
    ( 0, Cmd.none )

to call the port function

init : Value -> Url -> Nav.Key -> ( Model, Cmd Msg )
init flags url navKey =
    ( 0, cache "" )

then all is good, the cache port gets called on the JS side, and logging the port object to the console reports what would be expected: an object (cache) with subscribe and unsubscribe functions.

Why do I appear to need to call the port function (cache) in init in order to have access to the port on the JS side?

What am I missing (doing wrong)?

Thanks

Code below:

ELM:

port module Counter exposing (main)

import Browser
import Browser.Navigation as Nav
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
import Json.Decode exposing (Value)
import Url exposing (Url)


port cache : String -> Cmd msg



-- MODEL


type alias Model =
    Int


init : Value -> Url -> Nav.Key -> ( Model, Cmd Msg )
init flags url navKey =
    ( 0, Cmd.none )



-- UPDATE


type Msg
    = Increment
    | Decrement
    | Reset
    | ChangedUrl Url
    | ClickedLink Browser.UrlRequest


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Increment ->
            ( model + 1, Cmd.none )

        Decrement ->
            ( model - 1, Cmd.none )

        Reset ->
            ( 0, Cmd.none )

        ChangedUrl _ ->
            ( model, Cmd.none )

        ClickedLink _ ->
            ( model, Cmd.none )


subscriptions : Model -> Sub Msg
subscriptions model =
    Sub.none



-- VIEW


view : Model -> Browser.Document Msg
view model =
    { title = "Counter"
    , body =
        [ div []
            [ button [ onClick Decrement ] [ text "-" ]
            , div [] [ text (String.fromInt model) ]
            , button [ onClick Increment ] [ text "+" ]
            , button [ onClick Reset ] [ text "reset" ]
            ]
        ]
    }



-- MAIN


main : Program Value Model Msg
main =
    Browser.application
        { init = init
        , onUrlChange = ChangedUrl
        , onUrlRequest = ClickedLink
        , subscriptions = subscriptions
        , update = update
        , view = view
        }

JS:

var elmAppContainerId = 'elm-app-container'
var elmAppContainer = document.getElementById(elmAppContainerId)

if (elmAppContainer)
  {
    var app = Elm.Counter.init({node: elmAppContainer, flags: {}})

    console.log(app.ports) // undefined
    
    app.ports.cache.subscribe( function() { console.log("Cached" );} ); // Results in a TypeError
  }
else
  {
    console.log("Can't find element with ID: " + elmAppContainerId)
  }

Cross-browser compatibility fix for File.Select.file(s) in elm/file

via Elm Discourse - Latest posts by @tommy Tommy Messbauer on Fri, 08 Feb 2019 23:46:47 GMT

@evancz

Recent updates to elm/file and elm/json have broken this module in IE11. I’ve created PRs to fix it. I’d love if these could get merged and I’ll be happy to help explain or talk about this.


Port Support! Let's collaborate on better experiences with ports

via Elm Discourse - Latest posts by @dukedave Dave Tapley on Fri, 08 Feb 2019 21:23:16 GMT

I would welcome examples of ports too!

Additionally, regarding:

Developer finds a reference implementation or a similar problem and is happy

I’d rather generalize this to ‘finds advice on how to proceed’, which may include not only an example usage of ports, but also perhaps e.g. web components, or the suggestion that Elm isn’t actually the right tool for the job in the first place.

How to use elm/file?

via Elm Discourse - Latest posts by @ivadzy Ivan on Fri, 08 Feb 2019 15:52:47 GMT

It might be helpful for someone who is trying to understand how to work with files and maybe drag&drop. I experienced with this recently

Example
Demo

Any resources for json-schema or swagger specs?

via Elm Discourse - Latest posts by @rupert Rupert Smith on Fri, 08 Feb 2019 14:19:40 GMT

I pinged the author - this is the json-schema package to use:

https://package.elm-lang.org/packages/json-tools/json-schema/latest/

Its a more up to date fork of:

https://package.elm-lang.org/packages/1602/json-schema/latest/

presumably to publish under the json-tools name.

Seems like this is good replacement for NoRedInk/json-elm-schema and provides decoding and encoding of json-schema, as well as a builder DSL for constructing them. So that is a nice starting point for OpenAPI 3.0.

 newer latest older