Skip to content

Instantly share code, notes, and snippets.

@JordanMartinez
Created July 23, 2022 18:10
Show Gist options
  • Save JordanMartinez/d367a2668942b31d9a77c53050053db4 to your computer and use it in GitHub Desktop.
Save JordanMartinez/d367a2668942b31d9a77c53050053db4 to your computer and use it in GitHub Desktop.
Array transpose implementation
module Main where
import Prelude
import Data.Array as A
import Data.Maybe (Maybe(..), maybe)
import Effect (Effect)
import Effect.Class.Console (log)
import TryPureScript as TryPureScript
main :: Effect Unit
main = TryPureScript.render =<< TryPureScript.withConsole do
test [[]] []
test [[1], [2], [3]] [[1, 2, 3]]
test [[1], [2], [3, 4]] [[1, 2, 3], [4]]
test [[1, 2], [3, 4], [5, 6, 7]] [[1, 3, 5], [2, 4, 6], [7]]
test [[1, 2], [3, 4, 7], [5, 6]] [[1, 3, 5], [2, 4, 6], [7]]
test :: Array (Array Int) -> Array (Array Int) -> Effect Unit
test i o = do
log $ "(transpose " <> (show i) <> ") == " <> show o <> " is " <> show ((transpose i) == o)
transpose :: forall a. Array (Array a) -> Array (Array a)
transpose xs = go 0 []
where
go :: Int -> Array (Array a) -> Array (Array a)
go idx allArrays = case buildNext idx of
Nothing -> allArrays
Just next -> go (idx + 1) (A.snoc allArrays next)
buildNext :: Int -> Maybe (Array a)
buildNext idx = do
xs # flip A.foldl Nothing \acc nextArr -> do
maybe acc (\el -> Just $ maybe [el] (flip A.snoc el) acc) $ A.index nextArr idx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment