Skip to content

Instantly share code, notes, and snippets.

@kayvank
Created December 22, 2024 21:42
Show Gist options
  • Save kayvank/39bebdce7c0b4eced9397e3ab288bec1 to your computer and use it in GitHub Desktop.
Save kayvank/39bebdce7c0b4eced9397e3ab288bec1 to your computer and use it in GitHub Desktop.
Haskell Vectors
#!nix-shell --pure -p "haskellPackages.ghcWithPackages(pkgs:[pkgs.text pkgs.bytestring pkgs.vector])" -i runghc
{- |
haskell vectors
-}
import qualified Data.ByteString.Lazy.Char8 as C8Lazy
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import qualified Data.Maybe as Maybe
import System.Environment
import Control.Monad.IO.Class (liftIO)
main :: IO ()
main = do
[f] <- getArgs
s <- C8Lazy.readFile f
print . V.sum . parse $ s
vectorImutable
putStrLn "+++++++++++++++++++"
vectorMutable
{- | fill the a vector with numbers from input file
-}
parse :: C8Lazy.ByteString -> V.Vector Int
parse = V.unfoldr step
where
step !s = Maybe.maybe Nothing f (C8Lazy.readInt s)
f = \(i, s) -> Just(i, C8Lazy.tail s)
vectorImutable :: IO ()
vectorImutable = do
let v = V.fromList ['a' .. 'z']
let e = v V.! 1
let v1 = v V.//[(1, 'x')]
let e1 = v1 V.! 1
let v2 = V.slice 1 2 v1
print e
print e1
print v2
vectorMutable :: IO ()
vectorMutable = do
let v = V.fromList ['a' .. 'z']
mvv <- liftIO $ V.thaw v
MV.write mvv 1 'Z'
v' <- V.freeze mvv
print v'
@kayvank
Copy link
Author

kayvank commented Dec 22, 2024

This is a nix script. To execute:

chmod 755 ./vector.hs
seq 1 100000 >  ./data
./vector.hs data

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment