STUArray with polymorphic type

前端 未结 2 1962
误落风尘
误落风尘 2021-01-18 03:54

I want to implement an algorithm using the ST monad and STUArrays, and I want it to be able to work with both Float and Double

2条回答
  •  自闭症患者
    2021-01-18 04:57

    So here's the workaround I'm going with for now - creating a new typeclass for types for which (forall s. MArray (STUArray s) a (ST s)):

    class IArray UArray a => Unboxed a where
      newSTUArray :: Ix i => (i, i) -> a -> ST s (STUArray s i a)
      readSTUArray :: Ix i => STUArray s i a -> i -> ST s a
      writeSTUArray :: Ix i => STUArray s i a -> i -> a -> ST s ()
    
    instance Unboxed Float where
      newSTUArray = newArray
      readSTUArray = readArray
      writeSTUArray = writeArray
    
    instance Unboxed Double where
      newSTUArray = newArray
      readSTUArray = readArray
      writeSTUArray = writeArray
    

    While I'm not perfectly satisfied with this, I prefer it on rules because:

    • rules depend on optimizations
    • rules are not really supposed to change the algorithm (?). where in this case they would as boxed arrays have very different behaviour regarding lazyness etc.

提交回复
热议问题