Making custom Yesod Form: Could not deduce (Monad (FormInput m)) - forms

I am trying to make multi-file form input. I am using Handling a collection of data in a Yesod Form as a reference.
Here I am trying to make association list of field names to files.
multiFileInput :: Monad m => RenderMessage (HandlerSite m) FormMessage =>
[Text] -> FormInput m [(Text, FileInfo)]
multiFileInput = mapM $ secondM (ireq fileField) . (getFieldKey &&& id)
I get error:
Could not deduce (Monad (FormInput m))
arising from a use of ‘mapM’
But I don't know how to handle this. If I just add this as a constraint I have to propagade this constraint "(Monad (FormInput Handler))" up to a call site, where I don't know how to handle it. FormInput m is an instance of Monad, so I don't understand the issue.
fileInfos <- runInputPost $ multiKeyFileInput "files"
-> No instance for (Monad (FormInput Handler))
arising from a use of ‘multiKeyFileInput’
I will try to use runRequestBody instead, but it would be nice to understand the problem.

The FormInput data type was supposedly changed from Monad to Applicative, so you have to use traverse, which is an Applicative version of mapM.

Related

Partial application is not allowed while using Function

I get the following error message:
"failure in proveterminate Error: Partial application of function convert_btree_to_tree in its body is not allowed while using Function"
from the following piece of Coq script, but I have no idea what is wrong. Can anyone give me some advice?
Function convert_btree_to_tree (t: btree (non_terminal' non_terminal terminal) terminal) {measure (fun t => bheight _ _ t)}:
tree (non_terminal' non_terminal terminal) terminal:=
let tl:= decompose t in
let ttl:= map convert_btree_to_tree tl in
let ttl':= convert_list_tree_to_tree_list ttl in
match broot _ _ t with
| inl n => node _ _ n ttl'
| inr t => node_t _ _ t
end.
Documentation on Function is very limited in the Reference Manual, does anybody know of a more complete and detailed reference, if possible with comments and examples?
I don't know much about Function but in your match, you return a node and a node_t. Since you didn't give the definitions, I don't know if these two constructors are from the same type, but I think you have a typo and the second case should return node t _ _ t.
EDIT after feedback from Marcus:
node_t is a constructor of tree which signature is terminal -> tree: given a term foo of type terminal, node_t foo is of type tree. node has the signature non_terminal -> tree_list -> tree.
Do you have any implicit parameters declared ? Otherwise, in your match cases, you apply too many arguments to node and node_t, which might be interpreted as partial application.

Type for Traversable that maps to same kind of Traversable

Short version. Most generic collections in Scala have a map method which will, in fact, return a collection of the same type. (List[A].map(f:A=>B) returns a List[B], for example.) The Scala collection library was explicitly designed to achieve this. What if I want to write code that is polymorphic over any such collection? Can "Traversable whose map behaves like a functor's does" be expressed as a type?
Long version. I have a situation where it would be useful to have an abstraction representing a collection of objects of some Current type, such that if those objects were converted to some Desired type, then the collection could use those objects to construct an object of some Result type. I can achieve pretty much everything I want just by using the function type
(C => D) => R
but one defect of this approach is the excessive laziness (in the context my application) of the natural map method, which would be something like
def map[C2](f: C=>C2): (C2=>D)=>R = (g => this(f andThen g))
This delays the application of f to the objects of type C until the R is being computed. I'd rather apply f immediately.
So, for example, I might implement something like
class Foo[+C,-D,+R](cs: List[C], finalize: List[D]=>R) {
def apply(f: C=>D): R = finalize(cs.map(f))
def map[C2](f: C=>C2): Foo[C2,D,R] = Foo(cs.map(f), finalize)
}
So far so good. But now I think to myself, there's nothing special about List here; any type constructor that implemented some kind of map function would do. The only thing is that the function finalize might rely on the structure of the collection. Maybe the first element of the list is treated specially, for example, so if the List.map returned some more general type of collection, perhaps a very abstract one that didn't even have a notion of "first element", then finalize could fail. Likewise if it expects the list to be a certain length but I filter the list or something.
This kind of problem cannot arise if I write the code in its natural generality, something like
class Foo[+C,-D,+R,F[x] <: Traversable[x]](cs: F[C], finalize: F[D]=>R) {
...
}
because then I can't accidentally do anything weird with the F (unless I inspect its type at runtime or something, in which case I deserve what I get).
The only remaining problem is that cs.map(f) has static type Traversable[D], not F[D], although of course we expect that it's actually of type F[D] usually, and the Scala collection library was explicitly designed to ensure that that is so.
So my question is, can this requirement on F be expressed in the types?
Essentially, I want the Scala version of the Haskell code
data Foo f b r a = Foo (f a) (f b -> r)
instance (Functor f) => Functor (Foo f b r) where
g `fmap` (Foo fa fbr) = Foo (g `fmap` fa) fbr
dothething :: (Functor f) => Foo f b r a -> (a -> b) -> r
dothething foo g = fbr fb where Foo fb fbr = g `fmap` foo
with more or less the same guarantees and without laziness.
Are you looking for Functor from scalaz?
https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/Functor.scala
It allows you to do abstract over anything that can fulfill the type class definition.
def addTwo[F[_]](f: F[Int])(implicit F: Functor[F]): F[Int] = f.map(_+2)
Now my 'addTwo' method does not care what is being mapped, as long as there exists a functor instance. So both of these would work:
addTwo(List(1,2,3))
addTwo(Future { 1 } )
etc.

Passing records to ffi

When I pass a record to javascript, it works:
data Record = Record {
elem :: String
}
doSomethingForeign :: Record -> Fay ()
doSomethingForeign = ffi " callJsFun(%1) "
But when the function is not monomorphical, the record is not evaluated, one needs to do it manually:
class Passable a
instance Passable Record
instance Passable Text
doSomethingForeign' :: (Passable a) => a -> Fay ()
doSomethingForeign' = ffi " callJsFun(Fay$$_(%1)) "
This is the simple case, when the extra typing of Fay$$_ isn't that annoying, but if I pass more complex structures with type parameters to js, then adding just Fay$$_ won't solve it. I'd like to know the rule, when the evaluation to native js types is applied and where not.
The thunks will remain and type conversions won't happen if you have a type variable or Ptr X in the FFI, in contrast to a concrete type or Automatic a where the opposite applies.
I think what you want here is :: Passable a => Automatic a -> Fay () to force any thunks. It should be equivalent to separating this into two functions with a monomorphic argument. Using Automatic with a foreign type such as Text will only force the thunk and not do any type conversions.

Using monadic validation with Digestive Functors and Snap

I try quite a while now to wrap my head around how to use validation in a digestive functors form field, that requires access to another monad. To cut it short I have a digestive form like this
studentRegistrationForm :: Monad m => Form Text m StudentRegistrationData
studentRegistrationForm = StudentRegistrationData
<$> "school" .: choice schools Nothing
<*> "studentId" .: check studentIdErrMsg (not . T.null) (text Nothing)
<*> "firstName" .: check firstNameErrMsg (not . T.null) (text Nothing)
<*> "lastName" .: check lastNameErrMsg (not . T.null) (text Nothing)
<*> "email" .: check emailErrMsg (E.isValid . T.unpack) (text Nothing)
(studentId is basically the username)
and would like to use the function usernameExists of Snap.Snaplet.Auth to check if the entered username is unique.
Just for completeness, here is the corresponding data type:
data StudentRegistrationData = StudentRegistrationData
{ school :: School -- ^ school the student is enroled
, studentId :: Text -- ^ matriculation number of the student
, firstName :: Text -- ^ first name of the student
, lastName :: Text -- ^ last name of the student
, email :: Text -- ^ email for sending password
} deriving (Show)
I create my form in a handler like:
studentRegistrationHandler :: AppHandler ()
studentRegistrationHandler = do
(view, registrationData) <- runForm "form" SRF.studentRegistrationForm
maybe (showForm "registration" view) createUser registrationData
showForm :: String -> View Text -> AppHandler ()
showForm name view =
heistLocal (bindDigestiveSplices view) $ render template
where
template = BS.pack $ "student-" ++ name ++ "-form"
So the problem I have now is to understand how to access the state of the Auth snaplet inside the form. Is it passed already or do I have to passed it myself? Would the functions checkM respectively validateM in the Text.Digestive.Form help me there?
I have found several examples of how to use digestive functors and snap auth and session, like:
snap example
digestive functors tutorial
postgres example
Getting started with Snap-Auth
But none shows Snap.Snaplet.Auth and digestive functors working together directly, and I am still such a noob when it comes to monad transformers and lifting... maybe it is too easy for me to see. :(
I can upload a standalone example on github, which shows my problem if it helps to illustrate it. Any hints, pointers and suggestions are very welcome! :)
Hannes
add on: I created an example application demonstrating basic authentication functionality, you may have a look here: digestive-functors-snap-auth-example enjoy!
I haven't tried this out to see if everything type checks, but here's the general idea. You are correct that you want to use either checkM or validateM to do your monadic validation. The type signature for checkM is informative:
checkM :: Monad m => v -> (a -> m Bool) -> Form v m a -> Form v m a
This tells us that the validation function will need to have the type (a -> m Bool) and the m must be the same as the m in the form. This means that you need to change the type of your form to something like this:
studentRegistrationForm :: Form Text AppHandler StudentRegistrationData
Now let's write the validator. Since we plan on using the usernameExists function in our validator, we need to look at that type signature:
usernameExists :: Text -> Handler b (AuthManager b) Bool
This actually looks a lot like the (a -> m Bool) type signature that we need. In fact, it's an exact match because Handler b (AuthManager b) is a monad. But even though it matches the (a -> m Bool) pattern exactly doesn't mean we're done quite yet. When you run your form, you're in the AppHandler monad which is probably just a type alias for Handler App App where App is your application's top-level snaplet state type. So what we need to do is convert Handler b (AuthManager b) into Handler b b which will unify with Handler App App. The with function from the snaplet API is exactly what we need. This makes our validation function quite simple:
validUser :: Text -> Handler App App Bool
validUser = liftM not . with auth . usernameExists
With this, you can use checkM usernameErrMsg validUser just like you use check in the above code.

State monad - adapt functions that only work with parts of the state?

I have a general state which is essentially a 3-tuple, and a number of functions which each concern themselves with parts of that state. I'm trying to work out a set of generic adapters for such functions, so that I can use them in a State monad pipeline.
This is possibly entirely wrongheaded; feel free to make that case.
I apologize in advance for mix of Java and pidgin Scala. I'm actually doing this in Java as a learning exercise, but nobody has time to read all that. I've elided a lot of uninteresting complexity for the sake of discussion; don't worry about the domain modeling.
The state in question is this:
ImportState(row:CsvRow, contact:Contact, result:ImportResult)
ImportResult is one of ADD, MERGE, or REJECT.
The functions I've defined are these:
def rowToContact: ImportRow => Contact
def findMergeCandidates: Contact => (Contact, List[Contact])
// merges, or declines to merge, setting the result
def merge: (Contact, List[Contact]) => (Contact, ImportResult)
def persist: Contact => ImportResult
def commitOrRollback: ImportState => ImportState
def notifyListener: ImportState => Nothing
The adapters I've defined so far are pretty simple, and deal with individual properties of ImportState:
def getRow: ImportState => ImportRow
def getContact: ImportState => Contact
def setRow(f: _ => ImportRow): ImportState => ImportState
def setContact(f: _ => Contact): ImportState => ImportState
def setResult(f: _ => ImportResult): ImportState => ImportState
The (broken) pipeline looks something like this (in Java):
State.<ImportState>init()
.map( setRow( constant(row) ) )
.map( setContact( getRow.andThen(rowToContact) ) )
.map( getContact.andThen(findMergeCandidates).andThen(merge) ) // this is where it falls apart
.map( setResult( getContact.andThen(persist) ) )
// ... lots of further processing of the persisted contact
.map(commitOrRollback)
.map(notifyListener);
The immediate problem is that merge returns a tuple (Contact, ImportResult), which I'd like to apply to two properties of the state (contact and result), while keeping the third property, row.
So far, I've come up with a couple of approaches to adaptation of merge that both suck:
Define some functions that pack and unpack tuples, and use them directly in the pipeline. This option is extremely noisy.
Define a one-off adapter for ImportState and merge. This option feels like giving up.
Is there a better way?
Your question is tagged Haskell - I'm hoping that means you can read Haskell, and not that someone saw 'monads' and added it. On that assumption, I'll be speaking Haskell in this answer, since it's the language I think in these days ;)
There's a useful concept called "functional lenses" with a couple Haskell library implementations. The core idea is that a "lens" is a pair of functions:
data Lens a b = Lens { extract :: (a -> b), update :: (a -> b -> a) }
This represents a functional way of getting and updating "parts" of a structure. With a type like this, you can write a function such as:
subState :: Lens a b -> State a t -> State b t
subState lens st = do
outer <- get
let (inner, result) = runState st (extract lens outer)
put (update lens outer inner)
return result
Translating that into Java sounds like an interesting (and possibly quite challenging) exercise!
Interesting I wrote this exact operation last night using fclabels:
withGame :: (r :-> r', s :-> s') -> GameMonad r' s' a -> GameMonad r s a
withGame (l1,l2) act = do
(r,s) <- (,) <$> askM l1 <*> getM l2
(a, s') <- liftIO $ runGame r s act
setM l2 s'
return a
GameMonad is a new type that is a monad transformer stack of state, reader, IO. I'm also using a bit of applicative functor style code don't let it put you off, it's pretty much the same as mokus.
Take a look at replacing the tuple approach with case classes. You get a lot for free in a structure that is virtually as easy to define, in particular a compiler generated copy method which allows you to create a copy of an instance, changing only the fields you want to change.