简体   繁体   English

如何指定固定大小的向量的类型?

[英]How to specify the type of a vector of fixed size?

I am trying to use Data.Vector.Fixed as the input to a function and am struggling to specify the vector's dimension in the type signature.我正在尝试使用Data.Vector.Fixed作为函数的输入,并且正在努力在类型签名中指定向量的维度。

For example, I am trying to do something like the following:例如,我正在尝试执行以下操作:

acronym :: Vector (Peano 8) String -> String
acronym = foldl1 (++)

and thus specifying the vector's dimension (8) using peano numbers as defined in Data.Vector.Fixed.Cont .因此指定使用数字皮亚诺如定义的矢量的维数(8) Data.Vector.Fixed.Cont

However, attempting to compile this gives kind-mismatch errors:但是,尝试编译它会导致种类不匹配错误:

...:12: error:
    * Expected a type, but
      `Vector (Peano 8) String' has kind
      `Constraint'
    * In the type signature:
        acronym :: Vector (Peano 8) String -> String
   |
61 | acronym :: Vector (Peano 8) String -> String
   |            ^^^^^^^^^^^^^^^^^^^^^^^

...:20: error:
    * Expected kind `* -> *', but `Peano 8' has kind `PeanoNum'
    * In the first argument of `Vector', namely `(Peano 8)'
      In the type signature: acronym :: Vector (Peano 8) String -> String
   |
61 | acronym :: Vector (Peano 8) String -> String

How can I specify a fixed vector's size in a type signature?如何在类型签名中指定固定向量的大小?

You're probably looking for something like:您可能正在寻找类似的东西:

{-# LANGUAGE DataKinds, FlexibleContexts, GADTs #-}
import qualified Data.Vector.Fixed as V
acronym :: (V.Vector v String, V.Dim v ~ 8) => v String -> String
acronym = V.foldl1 (++)

The type class constraint Vector v String indicates that v is a vector with elements of type String , while the constraint Dim v ~ 8 ensures it has the right size.类型类约束Vector v String表示v是一个具有String类型元素的向量,而约束Dim v ~ 8确保它具有正确的大小。

It can be used with specific vector types, like boxed or continuation vectors, like so:它可以与特定的向量类型一起使用,例如盒装向量或连续向量,如下所示:

import qualified Data.Vector.Fixed.Boxed as BV
import qualified Data.Vector.Fixed.Cont as CV
eight = ["one","two","three","four","five","six","seven","eight"]
main = do
  print $ acronym (V.fromList eight :: BV.Vec 8 String)
  print $ acronym (V.fromList eight :: CV.ContVec 8 String)

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

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