5

I don't understand why the below program fails to compile.

module Main where

import Prelude
import Effect (Effect)
import Effect.Console (log)
import Data.Generic.Rep (class Generic)
import Foreign.Generic (defaultOptions, genericEncodeJSON)

main :: Effect Unit
main = do
  log "Hello sailor!"

newtype Foo = Foo {
    x :: Int
  , y :: Int
  , z :: Array Bar
}

type Bar = {
    a :: String
  , b :: String
}

derive instance repGenericFoo:: Generic Foo _

fooToJSON :: Foo -> String
fooToJSON = genericEncodeJSON $ defaultOptions { unwrapSingleConstructors = true }

This is the output by the compiler

Compiling Main
Error found:
in module Main
at src/Main.purs line 27, column 13 - line 27, column 30

  No type class instance was found for

    Foreign.Class.Encode { a :: String
                         , b :: String
                        }

If Array is not used, then the program compiles

newtype Foo = Foo {
    x :: Int
  , y :: Int
  , z :: Bar
}

type Bar = {
    a :: String
  , b :: String
}

why is it that genericEncodeJSON can't encode Bar if it's inside a container like Array or List?

Dan Robertson
  • 4,315
  • 12
  • 17
duggi
  • 556
  • 5
  • 13
  • I don’t know anything about purescript but In Haskell, `Foo` could not be a newtype and `Bar` is missing a constructor (or are JS-style objects allowed as types in purescript?) – Dan Robertson Aug 24 '18 at 21:56
  • @DanRobertson In purescript {} is a synonym for Record which is a type constructor. – duggi Aug 24 '18 at 22:21
  • What if you derive `Generic Bar` too? – Dan Robertson Aug 24 '18 at 22:31
  • @DanRobertson Deriving Generic Bar also doesn't compile (same error). If I make Bar an instance of Foreign.Class.Encode it compiles, but it defeats the purpose as I want to serialize my data automatically. – duggi Aug 24 '18 at 22:36
  • I'm facing the same problem and I've created an issue in their repo https://github.com/paf31/purescript-foreign-generic/issues/59 . By any chance, were you be able to solve it? – tonicebrian Nov 10 '20 at 20:33

0 Answers0