Haskell 使用 Foldmap 制表函数 "Out of Scope"

Haskell Tabulate function using Foldmap "Out of Scope"

我正在尝试为“制表”编写一个定义,该函数生成给定 Map 中值的幺半群摘要 对应给定 Foldable 集合中的键。

这是我的代码:

module Foldables where

import Prelude hiding (Applicative(..), any, concat)
import Data.Foldable
import Data.Semigroup

import qualified Data.Map as Map
import Data.Map (Map)
import Data.Map.Append (AppendMap(..))
import Data.List (intersperse)
import Data.Maybe (maybe)
import Data.Monoid (Any(..), Sum(..))
import GHC.Generics (Generic)

tabulate :: (Ord k, Foldable f, Monoid a) => (v -> a) -> Map k v -> f k -> a
tabulate t m = foldMap (tabulate . k v)

我收到这个错误:

src/Foldables.lhs:295:27: error:
    • Data constructor not in scope: Tabulate :: b0 -> a
    • Perhaps you meant variable ‘tabulate’ (line 295)

src/Foldables.lhs:295:38: error:
    Variable not in scope: k :: t0 -> k -> b0

除第二行括号内的内容外,请不要更改任何内容

更新:我想我更接近于理解这一点。这是我的新代码。我知道它不完整,但它至少可以编译。

tabulate :: (Ord k, Foldable f, Monoid a) => (v -> a) -> Map k v -> f k -> a
tabulate t m = foldMap (\x -> mempty maybe [m] maybe map [t])

现在它无法通过阴谋集团测试:

   Falsified (after 2 tests):
     <fun>
     fromList [(False,'\DC4'),(True,'54302')]
     [True,True]

无论我做什么似乎都会有所不同

我假设我需要的是某种条件,以防 tabulate 的第三个参数不空?

这里有一个提示(就是没有foldMap的解决方案,我估计是问题的对象):

如果我没听错的话,你想写下这样的东西:

tabulate :: (Ord k, Foldable t, Monoid a) => (v -> a) -> Map k v -> t k -> a
tabulate t m ks = let
                    c k x = (t <$> Data.Map.Strict.lookup k m) <> x
                  in case Prelude.foldr c Nothing ks of
                          Just s  -> s
                          Nothing -> mempty

我写下的案例在 ks 的交集时有效(顺便说一句,foldMap 的解决方案不需要这个参数 - 它会被删除,如你所愿在 post) 与 keys of the map (m) 是空的(也就是说,只有 Nothings 被聚集)。

在其他情况下,我们只是用一些东西折叠键的容器,类似于 mappend for Maybe - 它首先尝试在地图中查找给定的键。如果成功,它会将结果放入 Just,然后 fmap 将变换 t(给我们一个幺半群)放入其中。如果没有,则 returns Nothing。在 Maybemappend 序列中,所有 Nothing 都被丢弃,Just 中的结果与 mappend 连接。请参阅 Maybe<> 定义(<>Semigroup 的方法,它是 mappend 的基础,因为 MonoidSemigroup的子类):

-- | @since 4.9.0.0
instance Semigroup a => Semigroup (Maybe a) where
    Nothing <> b       = b
    a       <> Nothing = a
    Just a  <> Just b  = Just (a <> b)
    ...

我的 foldMap 解决方案:

tabulate :: (Ord k, Foldable t, Monoid a) => (v -> a) -> Map k v -> t k -> a
tabulate t m = foldMap (\ k -> maybe mempty t (Data.Map.Strict.lookup k m))

它执行以下操作:foldMap 的 function-argument 获取密钥 k。如果它不在地图中,则它 returns mempty。否则 - 它 returns t x,其中 Just xlookup 得到的。