2

GHCJS で動作するように、いくつかの JS ライブラリ用に JS FFI を構築しようとしています。リストを単一の JSVal に変換する必要があります。

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

しかし、エラーが発生します

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

明らかに、concat関数が必要ですが、使用mconcatすると

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

たぶん、この変換を適切に行う簡単な方法はありますか?

4

2 に答える 2

2

また、手元で変換することもできます:

{-# 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])
于 2016-08-10T20:05:28.057 に答える