Ask the assistant
0/400
Your question is processed by an AI service and kept to improve answers. Do not enter personal data.

    A function plot

    A larger example than the ones on the home page: state, controls, a computation, drawing and animation at once. Three buttons choose the function, a slider changes the parameter k , and the line flows into its new shape.

    The example is live: press Run, then change something in the code — the number of points, a colour, the formula itself — and run it again.

    // `State` declares the variables: the kind of function and the parameter k.
    State @kind:"sin" @k:2
      Column crossAxisAlignment:stretch spacing:12
        Row spacing:8
          TextButton onPressed:(){kind = "sin"}
            Text "sin(k·π·x)"
          TextButton onPressed:(){kind = "pow"}
            Text "x^k"
          TextButton onPressed:(){kind = "abs"}
            Text "k·|x|"
        // A slider keeps nothing: it hands the new value to a handler.
        Slider value:$k min:1 max:5 divisions:4 onChanged:(next){k = next}
        // 21 values of the function: x runs from -1 to 1 in steps of 0.1.
        State @ys:{map(range(21), (i){kind == "sin" ? sin(k * 3.14159 * (i / 10 - 1)) : (kind == "pow" ? pow(i / 10 - 1, k) : k * abs(i / 10 - 1))})}
          SizedBox height:180
            // `*Animated` leads the list to its new values: the line flows instead of jumping.
            *Animated of:$ys value:@line duration:500 curve:easeOutCubic
              *Stack
                *Points values:$line mode:area fill:0x226938EF
                *Points values:$line mode:line color:0xFF6938EF strokeWidth:2 cap:round join:round
        // A template string puts a value into text.
        Text $"k = ${k}"
    • @kind:"sin" and @k:2 declare variables; $k reads one, and an expression goes in braces.
    • A button and a slider do not "redraw" anything: they change a value, and everything that reads it follows.
    • map(range(21), (i){…}) is a function over a list: the markup itself computes the plot.
    • Elements with a star draw straight onto a canvas; *Points stretches the line to the height by itself.
    • Named parameters ( mode:area , cap:round ) set the look.

    Things to change

    • range(21) is the number of points. For a smooth line take range(81) and replace i / 10 - 1 with i / 40 - 1 in all three places of the formula: x still runs from -1 to 1.
    • duration:500 on *Animated is how long the line takes to flow into its new shape.
    • A fourth function: one more button with kind = "cos" and one more branch in the expression.
    DOCS
    dark_mode_baseline
    RU/EN
    menu_baseline