Arrays 按有界数据类型索引的Repa数组?

Arrays 按有界数据类型索引的Repa数组?,arrays,haskell,repa,Arrays,Haskell,Repa,我希望实现与标准数组包中的有界数组类似的功能,但使用的是repa数组 实现这一目标的好方法是什么 这是我尝试过的,但肯定有比在检查边界的自定义函数中包装所有内容更好的方法: import Data.Array.Repa data C = A | F | L deriving (Eq,Enum,Ord,Bounded,Show) data Ballot c = Ballot { vote::Array U (Z :. Int) Int } deriving Show mkB

我希望实现与标准数组包中的有界数组类似的功能,但使用的是repa数组

实现这一目标的好方法是什么

这是我尝试过的,但肯定有比在检查边界的自定义函数中包装所有内容更好的方法:

import  Data.Array.Repa

data C = A | F | L deriving (Eq,Enum,Ord,Bounded,Show)

data Ballot c = Ballot {
    vote::Array U (Z :. Int) Int
    } deriving Show

mkBallot::(Eq c ,Enum c,Ord c, Bounded c, Show c) => c -> Ballot c
mkBallot c = Ballot $ fromListUnboxed (Z :. max) (genSc c)
where
    max = (fromEnum (maxBound `asTypeOf` c)) + 1

genSc::(Eq c,Enum c,Ord c,Bounded c,Show c) => c -> [Int]
genSc c = [ f x | x <- enumFrom (minBound `asTypeOf` c) , let f v = if x == c then 1 else 0]

showScore c b = index (vote b) (Z :. ((fromEnum c)))
import Data.Array.Repa
数据C=A | F | L推导(等式、枚举、Ord、有界、显示)
数据选票c=选票{
投票::数组U(Z:.Int)Int
}衍生节目
mkBallot::(等式c、枚举c、命令c、有界c、显示c)=>c->Ballot c
mkBallot c=选票$fromlistunbox(Z:.max)(genSc c)
哪里
max=(fromnum(maxBound`asTypeOf`c))+1
genSc::(等式c,枚举c,Ord c,有界c,Show c)=>c->[Int]

genSc c=[fx | x您可以在有界枚举周围为包装器创建一个形状实例。我不确定这是最好的方法,但我认为它可以满足您的需要

{-# LANGUAGE ScopedTypeVariables  #-}

import Data.Array.Repa
这里我们在有界对象上创建一个shape实例,我们需要“full”数组的索引结束


我来看看这个。
data Idx a = Idx a | EOI
           deriving (Eq, Ord, Show)

fromIdx :: forall a . (Bounded a, Enum a) => Idx a -> Int
fromIdx EOI = fromEnum (maxBound :: a) - fromEnum (minBound :: a) + 1
fromIdx (Idx x) = fromEnum x - fromEnum (minBound :: a)

toIdx ::  forall a . (Bounded a, Enum a) => Int -> Idx a
toIdx i | i < 0 = error "negative index"
toIdx i = case compare i range of
  LT -> Idx $ toEnum (i + fromEnum (minBound :: a))
  EQ -> EOI
  GT -> error "out of range"
  where
    range = fromEnum (maxBound :: a) - fromEnum (minBound :: a) + 1

instance (Bounded a, Enum a, Ord a) => Shape (Idx a) where
  rank _ = 1
  zeroDim = Idx minBound
  unitDim = Idx $ succ minBound
  intersectDim EOI n = n
  intersectDim n EOI = n
  intersectDim (Idx n1) (Idx n2) = Idx $ min n1 n2
  addDim = error "undefined"
  size = fromIdx
  sizeIsValid _ = True
  toIndex _ n = fromIdx n
  fromIndex _ i = toIdx i
  inShapeRange _ _ EOI = error "bad index"
  inShapeRange n1 n2 n = n >= n1 && n <= n2
  listOfShape n = [fromIdx n]
  shapeOfList [i] = toIdx i
  shapeOfList _ = error "unsupported shape"
  deepSeq (Idx n) x = n `seq` x
  deepSeq _ x = x
data C = A | F | L deriving (Eq, Enum, Ord, Bounded, Show)

data Ballot c = Ballot { vote :: Array U (Idx c) Int
                       } deriving Show

mkBallot :: (Eq c, Enum c, Ord c, Bounded c, Show c) => c -> Ballot c
mkBallot c = Ballot $ fromListUnboxed EOI vec
  where
    vec = map (fromEnum . (== c)) [minBound .. maxBound]