SImple recursive sum when compiled from Haskell to WASM is quadratic

  Kiến thức lập trình

The following Haskell funcion:

{-# LANGUAGE ForeignFunctionInterface #-}
module Main where

import Data.Word (Word32)

sum' :: Word32 -> Word32
sum' 0 = 0
sum' n = n + sum' (n-1)

foreign export javascript "sum" sum' :: Word32 -> Word32

main :: IO ()
main = print (sum' 10000000)

When compiled to WASM is quadratic on n, instead of linear, as expected. Because of that, it is millions of times slower than the native version, which isn’t expected for WASM. Is this a compiler bug, or am I doing something wrong?

I’m using GHC 9.11.20240817, with the following command:

wasm32-wasi-ghc main.hs -O2 -no-hs-main -optl-mexec-model=reactor

Followed by the post-linking step:

$(wasm32-wasi-ghc --print-libdir)/post-link.mjs -i main.wasm -o main.js

I’m then importing sum from JS and calling it on different n’s.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT