Posts

Showing posts with the label haskell

Using Proxy in a TypeClass

Using Proxy in a TypeClass I'm trying to do something similar to this question. I'd like to define a typeclass class Wrapper f where wrap :: a -> f a unwrap :: f a -> a name :: Proxy (f a) -> String and then define instance (IsString a, FromJSON a, Wrapper f) => FromJSON (f a) where parseJSON (String s) = wrap <$> pure (fromString $ unpack s) parseJSON invalid = typeMismatch (name (Proxy :: Proxy (f a))) invalid But I'm getting an error saying that Could not deduce (Wrapper f0) arising from a use of ‘name’ from the context: (IsString a, FromJSON a, Wrapper f) bound by the instance declaration at src/Model/Wrapper.hs:29:10-62 The type variable ‘f0’ is ambiguous It's not really clear to me why this doesn't work and if it possible to fix it somehow ...

Servant QueryParams parse error

Servant QueryParams parse error Given the following code: newtype HelloMessage = HelloMessage { msg :: String } deriving (Generic) instance ToJSON HelloMessage type API2 = "hello" :> QueryParam "age" Int :> Get '[JSON] HelloMessage appAPI2 :: Proxy API2 appAPI2 = Proxy myHandler :: Server API2 myHandler = helloHandler where helloHandler :: Maybe Int -> Handler HelloMessage helloHandler mAge = let sAge = case mAge of Nothing -> "0" Just ag -> show ag in return . HelloMessage $ sAge app2 :: Application app2 = serve appAPI2 myHandler main :: IO () main = run 8080 app2 I can access /hello which returns { "msg" : 0} or /hello?age=20 which returns { "msg" : 20} . But if I set the age to be a non-integer parseable e.g. "foobar" which makes the url to be /hello?age=foobar and access it, it returns an error message ...

Efficient way of printing property names in Haskell

Efficient way of printing property names in Haskell Hello i am new to Haskell and i was wondering : For every new defined type constructor even if it is something with 0 depth eg.: data Letter =A | B | C deriving (Show) do i have to provide instance Show Type Letter A = "A" Letter B ="B" Letter C ="C" I understand that for nested types you have to provide Show implementation but for something simple is there no other way to just use something equivalent to reflection (C#) ? Just get the property name / constructor name and ToString -it ? Show ToString Do haskell programmers provide instances for Show for any adhoc type they create? Show By nested types i mean having a simple ADT inside another ADT inside another etc..but all you want is to get their names: e.g: data Person = Male | Female data IsMarried=Yes | No data Worker=Worker{ person::Person, status::IsMarried } For this kind of nesting do i really...