简体   繁体   中英

How can I parse custom type in a digestive-functors form?

I have no problems trying to parse built-in types in a digestive-functors form, eg I have a Client type (generated by the persistent library) that references a Country ID (of Key Country type):

Client
  :: String
     -> String
     -> String
     -> Database.Persist.Class.Key Country
     -> Maybe Int
     -> Client

Then I define a clientForm value:

clientForm :: Monad m => Form String m Client                                                                           
clientForm = Client <$> "firstName" .: string Nothing                                                                   
                    <*> "lastName"  .: string Nothing                                                              
                    <*> "address"   .: string Nothing                                                              
                    <*> "country"   .: stringRead "Cannot parse country" Nothing                                   
                    <*> "age"       .: optionalStringRead "Cannot parse age" Nothing        

Strangely, the clientForm when submitted (POST), cannot parse the country id field. 在此处输入图片说明

Is it wrong to use "stringRead" to parse "Key Country" type (which can be obtained from "toSqlKey int64")?

After some help from dmwit Freenode #haskell, the following will solve the problem:

clientForm :: Monad m => Form String m Client                                                                           
clientForm = Client <$> "firstName" .: string Nothing                                                                   
                <*> "lastName"  .: string Nothing                                                              
                <*> "address"   .: string Nothing                                                              
                <*> (toSqlKey <$> "country" .: stringRead "Cannot parse country id." Nothing)                                   
                <*> "age"       .: optionalStringRead "Cannot parse age" Nothing

I think the confusion came from the fact that "Key Country" type (a newtype) cannot be "read" directly from an integer...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM