数字参数化矢量的Monad实例? [英] Monad instance of a number-parameterised vector?
问题描述
data Nat s = > FSVec sa
FSVec
不是 Monad
类型类。
列表的monad实例可用于删除或重复元素:
Prelude> [1,2,3]>> = \ i - >情况1为1 - > [1,1]; 2 - > []; _ - > [i]
[1,1,3]
是否与列表版本相似或不是,是否有可能从一个固定长度的向量构造monad?
是的,如果不是自然的话,这是可能的。 / p>
单子必须对角化结果才能满足单子定律。
也就是说,你可以看一个向量作为 [0..n-1] - >的列表函数。 a
,然后修改monad实例的函数。
结果加入
操作一个向量矢量形式的矩形矩阵,并返回其对角线。
给定
tabulate :: Pos n => (全部m(m,m:<:n)=> m - > a) - > FSVec na
然后
instance Pos n => Monad(FSVec n)其中
return = copy(toNum undefined)
v>> = f = tabulate(\i-> f(v!i)!i)
可悲的是对此monad的使用有所限制。
我的流套件和Jeremy套件中的主题有六种版本Gibbons在这篇monad上写了一篇博客文章。
等效地,您可以将 FSVec n
视为 bindRep 和的定义来表示函数, pureRep
在我的可表示函子 pa ckage自动获得定义。
Statically sized vectors in Haskell are shown in Oleg Kiselyov's Number-parameterized types and can also be found in the Data.Param.FSVec
type from the parameterized-data module on Hackage:
data Nat s => FSVec s a
FSVec
is not an instance of the Monad
type class.
The monad instance for lists, can be used to remove or duplicate elements:
Prelude> [1,2,3] >>= \i -> case i of 1 -> [1,1]; 2 -> []; _ -> [i]
[1,1,3]
Whether similar to the list version or not, is it possible to construct a monad from a fixed length vector?
Yes it is possible, if not natural.
The monad has to 'diagonalize' the result in order to satisfy the monad laws.
That is to say, you can look at a vector as a tabulated function from [0..n-1] -> a
and then adapt the monad instance for functions.
The resulting join
operation takes a square matrix in the form of a vector of vectors and returns its diagonal.
Given
tabulate :: Pos n => (forall m. (Nat m, m :<: n) => m -> a) -> FSVec n a
then
instance Pos n => Monad (FSVec n) where
return = copy (toNum undefined)
v >>= f = tabulate (\i -> f (v ! i) ! i)
Sadly uses of this monad are somewhat limited.
I have a half-dozen variations on the theme in my streams package and Jeremy Gibbons wrote a blog post on this monad.
Equivalently, you can view a FSVec n
as a representable functor with its representation being natural numbers bounded by n, then use the definitions of bindRep
and pureRep
in my representable-functors package to get the definition automatically.
这篇关于数字参数化矢量的Monad实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!