Created
September 29, 2017 14:23
-
-
Save harendra-kumar/0d898da59062377a806504dc8b539ab2 to your computer and use it in GitHub Desktop.
Mandatory and optional keyword arguments with default values for Haskell using rawr anonymous records
This file contains 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
#!/usr/bin/env stack | |
-- stack runghc --package rawr | |
-- --------------------------------------------------------------------------- | |
-- This code snippet demonstrates using keyword arguments with default values | |
-- in Haskell using the rawr anonymous records library. Supported features: | |
-- | |
-- 1) Specify arguments using keywords | |
-- 2) Make some arguments mandatory and others optional | |
-- 3) Assign default values to optional arguments | |
-- | |
-- On Unix, you can make this file executable and just execute it if you have | |
-- stack installed. | |
-- --------------------------------------------------------------------------- | |
{-# LANGUAGE DataKinds #-} | |
{-# LANGUAGE FlexibleContexts #-} | |
{-# LANGUAGE OverloadedLabels #-} | |
{-# LANGUAGE TypeOperators #-} | |
import Data.Rawr | |
-- --------------------------------------------------------------------------- | |
-- Record for name and email of maintainer | |
-- --------------------------------------------------------------------------- | |
type Maintainer = | |
R ( "name" := String | |
, "twitter" := String | |
, "address" := String | |
, "phone" := String | |
) | |
-- Specify default values for fields in Maintainer record above | |
-- You can use a subset of the fields if you so desire | |
type DefMaintainer = | |
R ( "address" := String | |
, "phone" := String | |
) | |
defMaintainer :: DefMaintainer | |
defMaintainer = | |
R ( #address := "" | |
, #phone := "" | |
) | |
-- function to create record of Maintainer type with defaults | |
maintainer t = go (R t) | |
where | |
go :: (Maintainer :~ DefMaintainer ::<= r) => r -> Maintainer | |
go r = defMaintainer :<= r | |
main = do | |
-- Optional fields take default values when omitted | |
putStrLn $ show $ | |
maintainer ( #name := "Harendra" | |
, #twitter := "https://twitter.com/hk_hooda") | |
-- Specify an optional arg as well | |
putStrLn $ show $ | |
maintainer ( #name := "Harendra" | |
, #twitter := "https://twitter.com/hk_hooda" | |
, #phone := "+919876012345" | |
) | |
-- Missed mandatory arguments produce a type error | |
-- putStrLn $ show $ maintainer (#name := "Harendra") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment