dotnet-websharper / core

WebSharper - Full-stack, functional, reactive web apps and microservices in F# and C#
https://websharper.com
Apache License 2.0
598 stars 50 forks source link

MathJS List.sumBy error with decimal #1303

Closed diegopego closed 1 year ago

diegopego commented 1 year ago

To reproduce, add the following test to dotnet-websharper-core\tests\WebSharper.Tests\MathJS.fs

        Test "decimal.list.sumby" {
            let total = [1m;2m;4m] |> List.sumBy id
            equal total 7m
        }

This throws the following error. WebSharper.Tests\MathJS.fs(309,39,309,52): warning WS9002: Could not find method for trait call: get_Zero targets: source:(() -> System.Decimal); types: System.Decimal

List.sumBy works fine with float.

I want to help solve this. I'd be glad if anyone could give me advice on it.

Jand42 commented 1 year ago

@diegopego Thanks for testing. Indeed, decimal proxy at

https://github.com/dotnet-websharper/core/blob/438fa773e17893638d902402e89236baae41d37a/src/stdlib/WebSharper.MathJS.Extensions/Decimal.fs#L69

needs a static Zero property. This could work:

    [<Inline>]
    static member Zero: decimal = 0m

Feel free to push a PR if indeed you see it passing.

diegopego commented 1 year ago

The error persisted after adding the suggested code. I googled and found this: "List.sum uses static member constraints. Static member constraints don't look into extensions methods so that's not an option." ... Use List.fold instead.

So I used and it worked.

let total = transactionItemsVar.Value
            |> List.map (fun v -> v.TotaPrice)
            |> List.fold (+) 0m<Money Quantity>

https://stackoverflow.com/questions/33403433/f-how-do-i-extend-a-type-with-get-zero-so-i-can-use-an-existing-type-generica

https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/type-extensions#generic-limitation-of-intrinsic-and-optional-type-extensions

Jand42 commented 1 year ago

@diegopego I have tested above Zero proxy now too with your test - it does work, I have pushed it now. Maybe you have not rebuilt properly, as compiler uses some special handling of WebSharper.Main.Proxies project, you must make sure WebSharper.Main is also rebuilt and it's best to shut down persistent compilation helper wsfscservice.exe too.

diegopego commented 1 year ago

All working! Thank you. It was my fault that it was not compiling.