The King lives! the Elvis operator
Description:
In other programming languages,
The King lives!
Let's add the Elvis operator to Haskell
(?:) :: ("SortOfBoolean" a) => a -> a -> a
left ?: right | left = left
| otherwise = right
If left
is truthy
, we get left
If left
is falsy
, we get right
Truthy and falsy values
Falsy values are, for starters:
False :: Bool
() :: ()
0 :: (Num a) => a
"" :: String
Non-falsy values are, well, truthy. You will need to define (?:)
for all of these types and their values
All sorts of algebraic datatypes can also be truthy / falsy:
[] :: [a]
is falsy; any non-empty list ofa
is truthyNothing :: Maybe a
is falsy; anyJust a
is truthy- any
Left a :: Either a b
is falsy; anyRight b
is truthy (a,b)
is falsy iffb
is falsy ( cf.Functor
, same asMaybe
andEither
really )
From Data.Ord
:
Down a
is falsy iffa
is falsy. Order does not affect truthfulness ( or something )
From Data.Monoid
:
Dual a
is falsy iffa
is truthy (!) This one might actually come in handy sometime
( We skip the rest of theMonoid
wrappers; they don't really add anything )
You will also need to define (?:)
for all of these types and their values
Non-strictness
In keeping with normal Haskell behaviour:
in left ?: right
, right
must not be evaluated if left
is truthy ( "short-circuiting" )
in Just a
, Left a
and Right b
, a
and b
must not be evaluated
in (a,b)
, a
must not be evaluated
in general, avoid needlessly evaluating values
Notes
Char
does not really have a falsy value ( <NUL>
just does not compute ); there will be no tests with Char
s
In Num
, Int
Integer
Word
Float
Double
and the algebraic Ratio
and Complex
will be tested, but not Int8
Word8
and friends
This kata started as a problem, not a solution. I have not looked deeply into Functor
Applicative
Monad
Foldable
and Traversable
types and values ( yet ). There may be room for a sequel. Suggestions are welcome.
Similar Kata:
Stats:
Created | Nov 5, 2018 |
Published | Nov 5, 2018 |
Warriors Trained | 89 |
Total Skips | 23 |
Total Code Submissions | 128 |
Total Times Completed | 24 |
Haskell Completions | 24 |
Total Stars | 4 |
% of votes with a positive feedback rating | 68% of 14 |
Total "Very Satisfied" Votes | 6 |
Total "Somewhat Satisfied" Votes | 7 |
Total "Not Satisfied" Votes | 1 |
Total Rank Assessments | 14 |
Average Assessed Rank | 5 kyu |
Highest Assessed Rank | 4 kyu |
Lowest Assessed Rank | 7 kyu |