简体   繁体   English

消化函数复选框列表

[英]List of checkboxes with digestive-functors

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"] . 将返回["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. 没有标准的方法可以这样做,但是digestive-functors使用Applicative界面是高度可组合的,因此您可以轻松地创建您想要的内容。

You can define a checkBox which returns a Maybe String , ie the name of the element if it was checked. 您可以定义一个checkBox ,它返回一个Maybe String ,即元素的名称(如果已选中)。

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: catMaybes :: [Maybe a] -> [a]可以帮助您进一步减少结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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