Skip to content

Instantly share code, notes, and snippets.

@pete-murphy
Created September 4, 2022 20:23
Show Gist options
  • Save pete-murphy/3e26f812cc60f0e84ae24a4e60eb7d72 to your computer and use it in GitHub Desktop.
Save pete-murphy/3e26f812cc60f0e84ae24a4e60eb7d72 to your computer and use it in GitHub Desktop.
Move indices around STArray
module Main where
import Prelude
import Data.Foldable (fold)
import Effect (Effect)
import TryPureScript (h1, h2, p, text, list, indent, link, render, code)
import Control.Monad.ST as ST
import Data.Array.ST as Array.ST
moveFromTo :: forall a. Int -> Int -> Array a -> Array a
moveFromTo sourceIndex targetIndex xs = ST.run do
xs' <- Array.ST.thaw xs
x <- Array.ST.splice sourceIndex 1 [] xs'
_ <- Array.ST.splice targetIndex 0 x xs'
Array.ST.freeze xs'
data MoveOperation = Up | Down
move :: forall a. MoveOperation -> Int -> Array a -> Array a
move Up n = moveFromTo n (n - 1)
move Down n = moveFromTo n (n + 1)
main :: Effect Unit
main = render do
let xs = [1,2,3,4]
fold
[ p $ text ("Original: " <> show xs)
, p $ text ("Move 3→1: " <> show (moveFromTo 3 1 xs))
, p $ text ("Move up from 2: " <> show (move Up 2 xs))
, p $ text ("Move down from 2: " <> show (move Down 2 xs))
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment