与消化仿函数复选框的列表 [英] List of checkboxes with digestive-functors

查看:98
本文介绍了与消化仿函数复选框的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用消化仿函数来创建一个具有程序生成的复选框列表的表单,这将返回一个列表。例如:

  [x]牛奶
[]谷物
[x]绞肉

会返回 [Milk,Ground meat]

我期待的类型会是这样的:

  form ::(Functor m,Monad m)=> [字符串]  - > HappstackForm m Html BlazeFormHtml [String] 


解决方案

这样做的方式,但消化函数使用 Applicative 界面高度组合,因此您可以轻松创建您你可以定义一个 checkBox ,它返回一个 Maybe String ,即元素的名称,如果它被检查。

  checkBox ::(Functor m,Monad m)
=>字符串 - > HappstackForm m Html BlazeFormHtml(Maybe String)
checkBox str = fmap maybeStr(inputCheckBox False)< ++ label str
其中
maybeStr True =只是str
maybeStr False = Nothing

然后,您可以遍历一系列字符串,为列表中的每个元素创建一个复选框。

  listForm'::(Functor m,Monad m)
=> [String]
- > HappstackForm m Html BlazeFormHtml [Maybe String]
listForm'= foldr(\ x xs - > fmap(:) x * xs)(pure [])。 map checkbox

catMaybes :: [也许a] - >

  listForm ::(Functor m,Monad m)
=> [String]
- > HappstackForm m Html BlazeFormHtml [String]
listForm = fmap catMaybes。 listForm'

最后,我们可以实例化实际的表单:

  food :: [String] 
food = [Milk,Cereals,Ground meat]

foodForm ::(Functor m,Monad m)
=> HappstackForm m Html BlazeFormHtml [String]
foodForm = listForm food


How do I use digestive functors to create a form that has a programmatically generated list of checkboxes, which would return a list. For example:

[x] Milk
[ ] Cereals
[x] Ground meat

would return ["Milk", "Ground meat"].

I'm expecting the type would be something like:

form :: (Functor m, Monad m) => [String] -> HappstackForm m Html BlazeFormHtml [String]

解决方案

There is no standard way to do so, but digestive-functors is highly composable using the Applicative interface, so you can easily create what you want.

You can define a checkBox which returns a Maybe String, i.e. the name of the element if it was checked.

checkBox :: (Functor m, Monad m)
         => String -> HappstackForm m Html BlazeFormHtml (Maybe String)
checkBox str = fmap maybeStr (inputCheckBox False) <++ label str
  where
    maybeStr True  = Just str
    maybeStr False = Nothing

You can then loop over a list of strings to create a checkbox like this for each element in the list:

listForm' :: (Functor m, Monad m)
          => [String]
          -> HappstackForm m Html BlazeFormHtml [Maybe String]
listForm' = foldr (\x xs -> fmap (:) x <*> xs) (pure []) . map checkBox

The catMaybes :: [Maybe a] -> [a] helps you to reduce the result further:

listForm :: (Functor m, Monad m)
         => [String]
         -> HappstackForm m Html BlazeFormHtml [String]
listForm = fmap catMaybes . listForm'

And finally, we can instantiate the actual form:

food :: [String]
food = ["Milk", "Cereals", "Ground meat"]

foodForm :: (Functor m, Monad m)
         => HappstackForm m Html BlazeFormHtml [String]
foodForm = listForm food

这篇关于与消化仿函数复选框的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆