- c = Cylinder(10.0, 20.0)
- c = Cylinder(radius_cm=10.0, height_cm=20.0)
To dig into this a bit more, let's consider the following problem. We have to get Moonlight, a super-hero cat, from the city he's currently in, Denver, to San Francisco, where a kitten is stuck up a tree. Let's say we have a function to help us out:
- fly -- takes a cat to a destination city from a starting city
fly(moonlight, sanFrancisco, denver)
But wait a second, which city goes first when we call fly? Is it the destination city? Or the start city? Ooh, I don't remember... But no fear! Keyword arguments to the rescue!
python code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
sanFrancisco = "San Francisco, CA"
denver = "Denver, CO"
moonlight = "Moonlight"
def fly(who, to, from_):
return "%s flies to %s from %s"%(who, to, from_)
print(fly(who=moonlight, from_=denver, to=sanFrancisco))
# =>
# Moonlight flies to San Francisco, CA from Denver, CO
Note in the code above, we have to use "from_" instead of "from" because "from" is a reserved word that is part of the syntax of the Python language. When we call the fly function, we can include keywords or not to our liking (so long as a non-keyword argument does not come after a keyword argument).
Let's implement a similar sort of behavior in Haskell:
Haskell code:
data Dscr = Who | To | From deriving (Show, Eq)
type City = String
sanFrancisco :: City
sanFrancisco = "San Francisco, CA"
denver :: City
denver = "Denver, CO"
type CatName = String
moonlight :: CatName
moonlight = "Moonlight"
fly :: Dscr -> CatName -> Dscr -> City -> Dscr -> City -> String
fly Who n From c1 To c2 = n ++ " flies from " ++ c1 ++ " to " ++ c2
fly Who n To c2 From c1 = fly Who n From c1 To c2
main :: IO ()
main = do
putStrLn $ fly Who moonlight To sanFrancisco From denver
-- main =>
-- Moonlight flies from Denver, CO to San Francisco, CA
This is only a toy example and I haven't used anything like this in production code but it seems like it could be a nice way to describe a function call. This piece of code also demonstrates a limited ability to flip arguments around (the From and To arguments can be transposed as demonstrated in the function calls) although note that one has to program the combinations manually.
At any rate, this kind of coding style does come in handy when you have to send your super cat off to rescue kittens in San Francisco on short notice... Cheers!

0 comments:
Post a Comment