Slices in Haskell

In Haskell, we use lists as the primary sequence type. Lists are similar to slices in some ways, but with some key differences due to Haskell’s functional nature.

import Data.List (intercalate)

main :: IO ()
main = do
    -- In Haskell, an empty list is represented as [].
    -- It's not nil, but we can check if it's empty.
    let s = [] :: [String]
    putStrLn $ "uninit: " ++ show s ++ " " ++ show (null s) ++ " " ++ show (length s == 0)

    -- To create a list with a specific length, we can use replicate
    let s = replicate 3 ""
    putStrLn $ "emp: " ++ show s ++ " len: " ++ show (length s)

    -- We can set values in a list, but in Haskell this creates a new list
    let s = ["a", "b", "c"]
    putStrLn $ "set: " ++ show s
    putStrLn $ "get: " ++ s !! 2

    putStrLn $ "len: " ++ show (length s)

    -- In Haskell, we use the ++ operator to concatenate lists
    let s = s ++ ["d"]
    let s = s ++ ["e", "f"]
    putStrLn $ "apd: " ++ show s

    -- To copy a list in Haskell, we simply assign it to a new variable
    let c = s
    putStrLn $ "cpy: " ++ show c

    -- Haskell has built-in list slicing
    let l = take 3 $ drop 2 s
    putStrLn $ "sl1: " ++ show l

    let l = take 5 s
    putStrLn $ "sl2: " ++ show l

    let l = drop 2 s
    putStrLn $ "sl3: " ++ show l

    -- We can declare and initialize a list in one line
    let t = ["g", "h", "i"]
    putStrLn $ "dcl: " ++ show t

    -- Haskell has built-in list comparison
    let t2 = ["g", "h", "i"]
    if t == t2
        then putStrLn "t == t2"
        else putStrLn "t != t2"

    -- We can create multi-dimensional lists
    let twoD = [[i + j | j <- [0..i]] | i <- [0..2]]
    putStrLn $ "2d: " ++ show twoD

To run this Haskell program, save it to a file (e.g., lists.hs) and use the following commands:

$ ghc lists.hs
$ ./lists

Or you can use the Haskell interpreter:

$ runhaskell lists.hs

Note that while Haskell lists are similar to slices in some ways, they are immutable and have different performance characteristics. Haskell also provides other data structures like Vector for more efficient indexing and updating operations.

For more advanced list operations, you might want to explore the Data.List module, which provides many useful functions for working with lists in Haskell.