2

I'm trying to build JS FFI for some JS library to get it work with GHCJS and I need to convert list to single JSVal

listToJSVal :: PToJSVal a => [a] -> JSVal
listToJSVal = map pToJSVal

but get error

 Couldn't match type ‘[JSVal]’ with ‘JSVal’
    Expected type: [a] -> JSVal
      Actual type: [a] -> [JSVal]

obviously, I need concat function, but using mconcat gives

Could not deduce (Monoid JSVal) arising from a use of ‘mconcat’
    from the context (PToJSVal a)
      bound by the type signature for

Maybe, there is easier way how to do this conversion properly?

sigrlami
  • 1,822
  • 1
  • 17
  • 35

2 Answers2

2

Also you could convert it at hand:

{-# LANGUAGE QuasiQuotes #-}

import GHCJS.Marshal.Pure
import GHCJS.Types
import GHCJS.Foreign.QQ 
import GHCJS.Prim

listToJSVal :: PToJSVal a => [a] -> JSVal
listToJSVal xs = foldl push ar xs 
    where ar = [js'| [] |]
          push as x = [js'| { `as.push(`x); $r = `as } |]

printArray :: JSVal -> IO ()
printArray as = [js_| for(i = 0;i < `as.length;i++) { console.log(`as[i]) } |]

main = do 
     printArray $ listToJSVal ([1,2,3,4,5]::[Int])
pachopepe
  • 391
  • 4
  • 6
1

It appears that pToJSVal is only defined for base types.

For conversion of arbitrary values to JS, I would try the toJSVal and toJSValListOf functions defined in GHCJS/Marshal/Internal.hs (link)

ErikR
  • 51,541
  • 9
  • 73
  • 124