Skip to content

Instantly share code, notes, and snippets.

@Jonplussed
Last active August 29, 2015 14:21
Show Gist options
  • Save Jonplussed/05d3a6f3dad6442d06e5 to your computer and use it in GitHub Desktop.
Save Jonplussed/05d3a6f3dad6442d06e5 to your computer and use it in GitHub Desktop.
{-# LANGUAGE FlexibleInstances #-}
module DefaultArgs where
{-
Lots 'o languages give you functions with default arguments. For instance, in Ruby:
def foo(bar, baz=0, quux=1)
# stuff...
end
This is a terrible idea. Changing a default arg value can have a ton of cascading
effects. But it is convenient! So, in cases where it'd be really, really nice to have
default args, how can we get those in Haskell?
-}
data Vec4
= Vec4 { x :: Int, y :: Int, z :: Int, t :: Int }
deriving (Eq, Show)
class ToVec4 a where
toVec4 :: a -> Vec4
instance ToVec4 Vec4 where
toVec4 = id
instance ToVec4 (Int -> Vec4) where
toVec4 f = f 1
instance ToVec4 (Int -> Int -> Vec4) where
toVec4 f = f 0 1
{-
Examples:
toVec4 $ Vec4 3 2
=> Vec4 3 2 0 1
toVec4 $ Vec4 4 3 2 5
=> Vec4 4 3 2 5
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment