Repa --- How to create an instance of reading?

What is the best way to do

type Configuration = Array DIM1 (Double, Double, Double)

Read instance? So later I could get

data SimulationData = SD Configuration Double StdGen Int

to be an instance of Read.

+5
source share
1 answer

Such an instance will be an orphan instance , which you should usually avoid. However, it is quite simple to write it:

{-# LANGUAGE TypeOperators #-}

import Data.Array.Repa (Array, Shape, Elt, Z(..), (:.)(..))
import qualified Data.Array.Repa as R

instance Read Z where
  readsPrec _ r = do
    ("Z", s) <- lex r
    return (Z, s)

instance (Read tail, Read head) => Read (tail :. head) where
  readsPrec d =
    readParen (d > prec) $ \r -> do
      (tl, s) <- readsPrec (prec + 1) r
      (":.", t) <- lex s
      (hd, u) <- readsPrec (prec + 1) t
      return (tl :. hd, u)
    where prec = 3

instance (Shape sh, Read sh, Elt a, Read a) => Read (Array sh a) where
  readsPrec d =
    readParen (d > app) $ \r -> do
      ("Array", s) <- lex r
      (sh, t) <- readsPrec (app + 1) s
      (xs, u) <- readsPrec (app + 1) t
      return (R.fromList sh xs, u)
    where app = 10

If you use the extension StandaloneDeriving, you can simplify the first two instances:

deriving instance Read Z
deriving instance (Read tail, Read head) => Read (tail :. head)

, , repa; , Text.Show repa show. repa ( , ).


, , ( toList) ; . "" , cereal, , ; Read .

+6

All Articles