How would you structure an elm spreadsheet application?

I look at elm trees and I really enjoy learning the language. I was thinking of making a spreadsheet application, but I cannot plunge into the head of how it will be structured.

Say we have three cells; A, B, and C. If I enter 4 into cell A and =A in cell B, how would I get cell B to always be equal to cell A? If I then enter =A+B in cell C, can this be evaluated to 8 , and also updated when A or B changes? Not sure how to use leverage for such dynamic behavior. Regards Oscar

+6
source share
1 answer

First you need to decide how to represent the spreadsheet grid. If you work against C, you can use a 2D array, but I found that the dictionary really works better in Elm. So you can define type alias Grid a = Dict (Int, Int) a .

As for a , each cell has ... this is an opportunity to define a domain-specific language. So something like

 type Expr = Lit Float | Ref (Int, Int) | Op2 (Float -> Float -> Float) Expr Expr 

This means that the expression is either a float literal, or a link to another cell, or an operator. An operator can be any function on two floats and two other expressions that are evaluated recursively. Depending on what you are going to, you can instead define specific tags for each operation, for example, Plus Expr Expr | Times Expr Expr Plus Expr Expr | Times Expr Expr , or you can add additional OPN tags for operations of various arity (for example, negate).

So you can define type alias Spreadsheet = Grid Expr , and if you want to add an alias (Int, Int) to something that can help too. I also assume that you only need to float in your table.

Now you need functions to convert strings to expressions and vice versa. The traditional names for these functions are parse and eval .

 parse : String -> Maybe Expr -- Result can also work eval : Spreadsheet -> Grid Float evalOne : Expr -> Spreadsheet -> Maybe Float 

The analysis will be a little more complicated; The string module is your friend. Eval will include replication of the links on the spreadsheet and populating the results recursively. First, you want to ignore the possibility of capturing infinite loops. Also, this is just a sketch, if you find that signatures of different types work better, use them.

As for the presentation, I would start by reading only read-only, so you can verify that hard-coded spreadsheets are evaluated correctly. Then you can worry about editing, and the idea is that you just run the parser and the evaluator and get a new table for rendering. It should work because there is no state in the table other than the contents of each cell. (Minimizing recycled work is one of many ways you can expand it.) If you use elm-html, the table elements should be in order.

Hope this takes you in the right direction. This is an ambitious project and I would like to see it when you are done (send it to the mailing list). Good luck

+5
source

All Articles