Skip to content

Instantly share code, notes, and snippets.

@JettIsOnTheNet
Created June 17, 2024 15:20
Show Gist options
  • Save JettIsOnTheNet/121def440a4f2fa5283ffd418d57c5af to your computer and use it in GitHub Desktop.
Save JettIsOnTheNet/121def440a4f2fa5283ffd418d57c5af to your computer and use it in GitHub Desktop.
Syntax example scan sheet for Haskell.
-- Haskell scan sheet / Cheat sheet
import System.IO
import Control.Concurrent
import qualified Data.Map as Map
-- variables and constants
integerVar :: Int
integerVar = 10
stringVar :: String
stringVar = "Hello, Haskell!"
-- functions
greet :: String -> String
greet name = "Hello " ++ name
-- recursion (loop)
count :: Int -> IO ()
count 0 = putStrLn "Finished counting"
count n = do
putStrLn $ "Count: " ++ show n
count (n - 1)
-- conditional statements
checkNumber :: Int -> String
checkNumber n
| n > 5 = "Number is greater than 5"
| n == 5 = "Number is exactly 5"
| otherwise = "Number is less than 5"
-- data structures
numbers :: [Int]
numbers = [1, 2, 3, 4, 5]
myMap :: Map.Map String Int
myMap = Map.fromList [("a", 1), ("b", 2)]
-- error handling using maybe
safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv x y = Just (x `div` y)
-- file I/O
writeToFile :: IO ()
writeToFile = do
let content = "Writing to a file in Haskell!"
writeFile "example.txt" content
readFromFile :: IO ()
readFromFile = do
content <- readFile "example.txt"
putStrLn $ "File content: " ++ content
-- concurrency
createThread :: IO ()
createThread = do
forkIO $ putStrLn "Running in a separate thread"
putStrLn "This is the main thread"
main :: IO ()
main = do
putStrLn $ greet "World"
count 5
putStrLn $ checkNumber integerVar
putStrLn "Performing file operations:"
writeToFile
readFromFile
createThread
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment