使单个函数在列表,ByteStrings和Texts(以及其他类似的表示)上工作, [英] Making a single function work on lists, ByteStrings and Texts (and perhaps other similar representations)
问题描述
我正在写一个函数,它可以在一系列任意符号中进行搜索。我想使它足够通用,以便它可以在 Foldable s以及
ByteString
s和文本
秒。将它推广到 Foldable
很简单。但是如何包含 ByteString
s和 Text
s?当然我可以将 ByteString
转换成列表,然后调用我的函数,但是我会失去所有优点 ByteString
s 。
I'm writing a function that does some searching in a sequence of arbitrary symbols. I'd like to make it generic enough so that it works on lists, Foldable
s as well on ByteString
s and Text
s. Generalizing it to Foldable
is simple. But how to include ByteString
s and Text
s? Sure I could convert ByteString
into a list and then call my function, but I'd lose all the advantages ByteString
s.
有一个具体的例子,假设我们想创建一个直方图函数:
To have a concrete example let's say we want to make a histogram function:
import Control.Monad.State
import qualified Data.Foldable as F
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Word
import qualified Data.ByteString as B
import qualified Data.Text as T
type Histogram a = Map a Int
empty :: (Ord a) => Histogram a
empty = Map.empty
histogramStep :: (Ord a) => a -> Histogram a -> Histogram a
histogramStep k = Map.insertWith (+) k 1
histogram :: (Ord a, F.Foldable t) => t a -> Histogram a
histogram = F.foldl (flip histogramStep) empty
但既然 ByteString
也可以是可折叠(它只存储
Word8
s / Char
s,而不是任意元素),我坚持创建更多像 的函数,只是使用了不同的类型签名:
But since neither ByteString
nor Text can be Foldable
(it stores just Word8
s/Char
s, not arbitrary elements), I'm stuck with creating more functions that look exactly like the one before, just with a different type signatures:
histogramBS :: B.ByteString -> Histogram Word8
histogramBS = B.foldl (flip histogramStep) empty
histogramText :: T.Text -> Histogram Char
histogramText = T.foldl (flip histogramStep) empty
这是一件事不希望像Haskell这样的函数式语言。
This is something one does not expect in a functional language like Haskell.
如何使它成为泛型,要写直方图
一次并为所有?
How to make it generic, to write histogram
once and for all?
推荐答案
您的解决方案几乎是 ListLike 包。还有一些额外的软件包 listlike-instances ,它为<$ c添加了实例$ c> Text 和 Vector
。
Your solution is pretty much what the ListLike package does. There's also the additional package listlike-instances which adds instances for Text
and Vector
.
这篇关于使单个函数在列表,ByteStrings和Texts(以及其他类似的表示)上工作,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!