vitoria-training / sprout

0 stars 0 forks source link

Experiment: transpose in Elm #19

Closed BeerShigachi closed 9 months ago

BeerShigachi commented 10 months ago

We want to know how to transpose a matrix in Elm in order to render contents in web pages vertical/horizontal. Here's specific features we need to research.

YuikeiMatsumoto commented 9 months ago
module Main exposing (..)
import Browser
import Html exposing (Html, div, text)
import List

type alias Model =
    List (List Int)

initialModel : Model
initialModel = [[10, 11], [20], [], [30, 31, 32]]

transpose : List (List a) -> List (List a)
transpose ll =
    let
        heads = List.map (List.take 1) ll |> List.concat
        tails = List.map (List.drop 1) ll
    in
    if List.isEmpty heads then
        []
    else
        heads :: (transpose tails)

view : Model -> Html Msg
view model =
    let
        transposedModel = transpose model
        rows =
            List.map
                (\row ->
                    div []
                        (List.map (\value -> div [] [ text (String.fromInt value) ]) row)
                )
                transposedModel
    in
    div []
        rows

type Msg = NoOp

update : Msg -> Model -> Model
update msg model =
    model

main =
    Browser.sandbox { init = initialModel, update = update, view = view }

This code performs matrix transpose.