Is it safe to interleave manual realWorld# state passing with an arbitrary Monad

Is it safe to interleave manual realWorld# state passing with an arbitrary Monad

Content Index :

Is it safe to interleave manual realWorld# state passing with an arbitrary Monad
Tag : arrays , By : pttr
Date : November 29 2020, 04:01 AM

should help you out TLDR; From what I gathered so far, it does seem to be a safe way to generate a primitive Vector in a way I originally proposed. Moreover, the use of noDuplicate# is not really necessary, since all of the operations are idempotent and order of operations will not have an affect on the resulted array(s).
Disclosure: It's been over a year since I first thought about that problem. It was only last month that I tried to get back to it. Reason why I am saying this is because checking out primitive package now I noticed a new module Data.Primitive.PrimArray to me. As @chi mentioned in the comments, there isn't really a need to drop down to the low-level primitives in order to get a solution, since it might already exist. Which contains exactly the function generatePrimArrayA, which was exactly what I was looking for (a bit simplified copy of the source code):
newtype STA a = STA {_runSTA :: forall s. MutableByteArray# s -> ST s (PrimArray a)}

runSTA :: forall a. Prim a => Int -> STA a -> PrimArray a
runSTA !sz =
  \(STA m) -> runST $ newPrimArray sz >>= \(ar :: MutablePrimArray s a) -> m (unMutablePrimArray ar)

generatePrimArrayA :: (Applicative f, Prim a) => Int -> (Int -> f a) -> f (PrimArray a)
generatePrimArrayA len f =
  let go !i
        | i == len = pure $ STA $ \mary -> unsafeFreezePrimArray (MutablePrimArray mary)
        | otherwise =
            (\b (STA m) -> STA $ \mary -> writePrimArray (MutablePrimArray mary) i b >> m mary)
            (f i)
            (go (i + 1))
   in runSTA len <$> go 0
generatePrimArrayA :: forall f a. (Applicative f, Prim a) => Int -> (Int -> f a) -> f (PrimArray a)
generatePrimArrayA !(I# n#) f =
  let go i# = case i# <# n# of
                0# -> pure $ \mary s# ->
                        case unsafeFreezeByteArray# mary s# of
                          (# s'#, arr'# #) -> (# s'#, PrimArray arr'# #)
                _ -> liftA2
                     (\b m ->
                        \mary s ->
                          case writeByteArray# mary i# b s of
                            s'# -> m mary s'#)
                     (f (I# i#))
                     (go (i# +# 1#))
   in (\m -> runRW# $ \s0# ->
                case newByteArray# (n# *# sizeOf# (undefined :: a)) s0# of
                  (# s'#, arr# #) -> case m arr# s'# of
                                       (# _, a #) -> a)
      <$> go 0#
generatePrimM :: forall m a . (Prim a, Applicative m) => Int -> (Int -> m a) -> m (PrimArray a)
generatePrimM (I# sz#) f =
  let go i# = case i# <# sz# of
                0# -> runRW# $ \s0# ->
                      case newByteArray# (sz# *# sizeOf# (undefined :: a)) s0# of
                        (# s1#, mba# #) -> pure (MutableByteArrayState s1# mba#)
                _  -> liftA2
                      (\b (MutableByteArrayState si# mba#) ->
                         MutableByteArrayState (writeByteArray# mba# i# b si#) mba#)
                      (f (I# i#))
                      (go (i# +# 1#))
   in (\(MutableByteArrayState s# mba#) ->
         case unsafeFreezeByteArray# mba# s# of
           (# _, ba# #) -> PrimArray ba#) <$>
      (go 0#)

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Operational monad with interpreter in arbitrary monad

Tag : haskell , By : Maplye
Date : March 29 2020, 07:55 AM
this one helps. That's because the m in the local type signatures are fresh type variables, so they promise to work with any Monad. If you use display, eval can only work for the specific monad display uses. It should work if you a) remove the local type signatures, or b) bring the type variable m into scope
{-# LANGUAGE ScopedTypeVariables #-}
interpret :: forall m. (Int -> m ()) -> Elo a -> Int -> m a

Create my own state monad transformer module hiding underlying state monad

Tag : haskell , By : Juice
Date : March 29 2020, 07:55 AM
may help you . I think that if you can write an instance of MonadState for your transformer you can use modify without the lift:
instance Monad m => MonadState (ZipperT s m a) where
MonadState (ZipperState s) (ZipperT s m)
instance MonadState s m => MonadState s (ZipperT s m) where
getZ :: Monad m => ZipperT s m (ZipperState s)
getZ = ZipperT_ get

putZ :: Monad m => ZipperState s -> ZipperT s m ()
putZ = ZipperT_ . put

modifyZ :: Monad m => (ZipperState s -> ZipperState s) -> ZipperT s m ()
modifyZ = ZipperT_ . modify
-- This requires UndecidableInstances
instance MonadState s m => MonadState s (ZipperT a m) where
   get = lift get
   put = lift . put
length' :: [a] -> Int
length' xs = runIdentity (execStateT (runZipperT contar ([], xs)) 0)
    where contar :: ZipperT a (StateT Int Identity) ()
          contar = headR >>= \x -> case x of
                     Nothing -> return ()
                     Just  _ -> do
                                    modify (+ (1::Int))
                                 -- ^^^^^^^

Why must we use state monad instead of passing state directly?

Tag : haskell , By : lifchicker
Date : March 29 2020, 07:55 AM
seems to work fine State passing is often tedious, error-prone, and hinders refactoring. For example, try labeling a binary tree or rose tree in postorder:
data RoseTree a = Node a [RoseTree a] deriving (Show)

postLabel :: RoseTree a -> RoseTree Int
postLabel = fst . go 0 where
  go i (Node _ ts) = (Node i' ts', i' + 1) where

    (ts', i') = gots i ts

    gots i []     = ([], i)
    gots i (t:ts) = (t':ts', i'') where
      (t', i')   = go i t
      (ts', i'') = gots i' ts
preLabel :: RoseTree a -> RoseTree Int
preLabel = fst . go 0 where
  go i (Node _ ts) = (Node i ts', i') where -- first change

    (ts', i') = gots (i + 1) ts -- second change

    gots i []     = ([], i)
    gots i (t:ts) = (t':ts', i'') where
      (t', i')   = go i t
      (ts', i'') = gots i' ts
branch = Node ()
nil  = branch []
tree = branch [branch [nil, nil], nil]
preLabel tree == Node 0 [Node 1 [Node 2 [],Node 3 []],Node 4 []]
postLabel tree == Node 4 [Node 2 [Node 0 [],Node 1 []],Node 3 []]
import Control.Monad.State
import Control.Applicative

postLabel' :: RoseTree a -> RoseTree Int
postLabel' = (`evalState` 0) . go where
  go (Node _ ts) = do
    ts' <- traverse go ts
    i   <- get <* modify (+1)
    pure (Node i ts')

preLabel' :: RoseTree a -> RoseTree Int
preLabel' = (`evalState` 0) . go where
  go (Node _ ts) = do
    i   <- get <* modify (+1)
    ts' <- traverse go ts
    pure (Node i ts')
postLabel' :: RoseTree a -> RoseTree Int
postLabel' = (`evalState` 0) . go where
  go (Node _ ts) =
    flip Node <$> traverse go ts <*> (get <* modify (+1))

preLabel' :: RoseTree a -> RoseTree Int
preLabel' = (`evalState` 0) . go where
  go (Node _ ts) =
    Node <$> (get <* modify (+1)) <*> traverse go ts

Is the composition of an arbitrary monad with a traversable always a monad?

Tag : haskell , By : Dov
Date : March 29 2020, 07:55 AM
hope this fix your issue No, it's not always a monad. You need extra compatibility conditions relating the monad operations of the two monads and the distributive law sequence :: n (m a) -> m (n a), as described for example on Wikipedia.
Your previous question gives an example in which the compatibility conditions are not met, namely

confusion over the passing of State monad in Haskell

Tag : haskell , By : Viv
Date : March 29 2020, 07:55 AM
will be helpful for those in need It really boils down to understanding that state is isomorphic to s -> (a, s). So any value "wrapped" in a monadic action is a result of applying a transformation to some state s (a stateful computation producing a).
Passing a state between two stateful computations
f :: a -> State s b
g :: b -> State s c
f >=> g
\a -> f a >>= g
a -> State s c
m >>= k  = StateT $ \ s -> do
    ~(a, s') <- runStateT m s
    runStateT (k a) s'
a >> b
a >>= \_ -> b
tick :: State Int Int 
tick = get >>= \n ->
    put (n+1) >>
    return n
tick = do
    n <- get
    put (n + 1)
    return n
Related Posts Related QUESTIONS :
  • Kotlin array <init>ialization
  • Is array declaration in Kotlin with size possible just with initialization?
  • V-lang shows V panic: array index out of range error for valid indexing of array after V panic is encountered once
  • How to redistribute content of a 2-d array?
  • perl call variable name using another variable(array)
  • Converting a cell to a 4D array
  • Preallocating memory for variable that changes size every iteration (long text file)
  • cmp instruction not making jge jump within InsertionSort
  • How can I find if the index number for a specific item in an array also exists as an integer in the same array?
  • Why does min value return as zero and max return as a proper value
  • How to search inside array in reactjs
  • Subscript out of range, moving data from range to array
  • How to zip a 2D and a 1D array row-wise in Julia?
  • What goes wrong in my array comparison code?
  • Revising a Ruby method to represent integer partition as ordered string (without flattening?)
  • Is there an easy way to compute difference between two arrays
  • Insert a smallest possible positive integer into an array of unique integers
  • How to avoid adding to an array if element already exists
  • why val not affect to the array in KOTLIN?
  • Selecting elements from a vector based on condition on another vector
  • Converting multiple variables in SAS from 0/1 to 'Yes'/'No'
  • Excel VBA Arrays: Is there a simple way to delete a dataset by the index?
  • Ruby - how to slice an array and sum its elements on a condition
  • Selecting Distinct Items within Array using PowerShell and Linq
  • Processing large arrays in PowerShell
  • Flutter - Create list and 'addAll' in same instruction
  • Having multiple separate arrays of data, is there any other more efficient method to merge them into objects?
  • Array with `n` elements in Kotlin doesn't work
  • Parse a JSON object with the value as JSON string array
  • The longest length of most consecutive number which is bigger than zero in a series
  • Mapping function to list/array in haskell?
  • multi-select dropdown and form field shows as array?
  • json array character value ascending and descending order typescript
  • VBA ARRAY definition does not work for global definitions
  • VBA Error: How do I define and initialize an Array in VBA
  • Multiplication of corresponding values in an array
  • `replace` versus plain `loop` for copying large arrays in SBCL
  • Using VBA in Excel, how do you Hide columns that do not have a header specified in an array?
  • Unable to convert varchar to array in Presto Athena
  • How to insert objects in array next to objects with the same property value
  • How can I remove rows of a matrix in Matlab when the difference between two consecutive rows is more than a threshold?
  • Apply function to pairs of columns in Julia
  • Getting an specified object from array and take this as a variable
  • Divide array into sub arrays such that no sub array contains duplicate elements
  • How to pick multiple array elements in swift 4.2?
  • Creating and inputting data into nested arrays - Ruby
  • "array out of range" when I tried to build in an indicator (SMA of the RSI line) to my EA
  • How to do this in a better way
  • How to sort in-place using the merge sort algorithm?
  • transpose 1D array of leading dimension N
  • passing an array of structures (containing two mpz_t numbers) to a function
  • Finding whether a value is equal to the value of any array element in MATLAB
  • Scala: array.toList vs array.to[List]
  • How to get element from JSON array in array in array
  • Shuffle an array of unequally repeating entries, so they do not repeat
  • angular 8 array change in console but not in view
  • How to set array total elements in for loop
  • Is there a void return higher-order function?
  • Swift: "Value of type 'Any' has no subscripts" when attempting to retrieve Strings from a 2D array
  • Run Time Error 5 when initializing a 2D array
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com