Skip to content

Instantly share code, notes, and snippets.

@prendradjaja
Last active December 6, 2023 20:46
Show Gist options
  • Save prendradjaja/baa3e18b7dd3fc8797791c2838665199 to your computer and use it in GitHub Desktop.
Save prendradjaja/baa3e18b7dd3fc8797791c2838665199 to your computer and use it in GitHub Desktop.

Guards

main = do
  print $ mySignum (-2)
  print $ mySignum 0
  print $ mySignum 2

mySignum n
  | n < 0 = -1
  | n > 0 = 1
  | otherwise = 0

Records

-- Defining a record type
data Point2D = Point2D
  { x :: Int
  , y :: Int
  } deriving (Show)

main = do
  -- Create, read, update
  let p = Point2D 12 34
  print $ x p
  print $ y p
  let p2 = p { x = 999 }
  print $ x p2

Uncurry

uncurry converts a curried function to a function on pairs.

>>> map (uncurry max) [(1,2), (3,4), (6,8)]
[2,4,8]
import Data.Function ((&))

main =
  zip names favoriteNumbers
  & map (uncurry makeUsername)
  & print

names = ["alice", "bob", "charlie"]
favoriteNumbers = [5, 10, 15]

makeUsername name number =
  name ++ (show number)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment