Created
December 22, 2024 21:42
-
-
Save kayvank/39bebdce7c0b4eced9397e3ab288bec1 to your computer and use it in GitHub Desktop.
Haskell Vectors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a
nix
script. To execute: