Range Over Built in Haskell

Here we use range to sum the numbers in a slice. Arrays work like this too.

import Data.List (elemIndex)
import Data.Maybe (fromJust)

main :: IO ()
main = do
  let nums = [2, 3, 4]
  let sum = foldl (+) 0 nums
  putStrLn $ "sum: " ++ show sum

  -- Range on arrays and slices provides both the index and value for each entry.
  -- Above we didn’t need the index, so we ignored it.
  -- Sometimes we actually want the indexes though.
  mapM_ (\(i, num) -> if num == 3 then putStrLn $ "index: " ++ show i else return ()) (zip [0..] nums)

  -- Range on map iterates over key/value pairs.
  let kvs = [("a", "apple"), ("b", "banana")]
  mapM_ (\(k, v) -> putStrLn $ k ++ " -> " ++ v) kvs

  -- Range can also iterate over just the keys of a map.
  mapM_ (\(k, _) -> putStrLn $ "key: " ++ k) kvs

  -- Range on strings iterates over Unicode code points.
  let str = "go"
  mapM_ (\(i, c) -> putStrLn $ show i ++ " " ++ show c) (zip [0..] str)

To run the program, save the code in a file called Main.hs and use runhaskell to execute it.

$ runhaskell Main.hs
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 'g'
1 'o'

Now that we can run and build basic Haskell programs, let’s learn more about the language.