Function with parameters in Haskell -
i'm trying write few functions have parameters in haskell.
for example: make list kinds of colors, want function color orange list, how specify in function?
getcolor :: -> getcolor = orange
you want function takes list of many colours , returns single colour (presumably of choosing). should start data type represent colours.
data colour = red | orange | yellow | green | blue
now want function getcolour
type
getcolour :: colour -> [colour] -> colour
which takes colour
, list of colour
, picks out desired colour list. however, lists can empty, or list might not contain colour want! getcolour
return in case?
in haskell handle function may not return result using maybe
. new type of getcolour
is
getcolour :: colour -> [colour] -> maybe colour
which means getcolour
either return nothing
, or just colour
colour
list.
lastly, i'll mention there few ways write body of getcolour
, using pattern matching , explicit recursion, or standard library functions haskell's prelude
. assume you're new haskell, i'd recommend former. here's code started:
getcolour _ [] = nothing getcolour colour (x:xs) = ...
is enough write getcolour
yourself?
Comments
Post a Comment