Which Haskell construct/statement is equivalent to "switch" of C++? Is it "guards" or "case of"?

Viewed 215

I am trying to benchmark "switch" statement vs "if-else if" statement in many languages and see which construct has the fastest execution. I was trained in college that "switch" is faster.

So my question regarding Haskell: Which Haskell construct/statement is equivalent to "switch" of C++? Is it "guards" or "case of"?

3 Answers

tl;dr there are no real equivalents, but switch is most easily translated with case, and if is most easily translated with guards.

Most often, switching is done without any dedicated construct at all, but simply with multiple function clauses.

f :: Char -> String

...
f 'k' = "kay"
f 'l' = "el"
f 'm' = "em"
...

Which is in fact translated to a case expression by GHC internally,

f c = case c of
  ...
  'k' -> "kay"
  'l' -> "el"
  'm' -> "em"
  ...

Of course, all of this, like all of Haskell, is purely functional. It doesn't work like switch in C++, which is all about the side-effects.

...But Haskell can do side-effects too, only, they're not statements but expressions of a a suitable monadic type. case can thus be used even for imperative switching.

main :: IO ()
main = do
   putStrLn "Hi, what's your name?"
   userName <- getLine
   case words useName of
     [singleName] -> do
        putStrLn "Select if this is your first (F) or last (L) name."
        nameKind <- getLine
        ...
     [firstName, lastName] -> do
        putStrLn "You entered you full name, thanks."

Haskell's if most directly corresponds to C++' ?: ternary operator, rather than its if construct. But again, this can be used for expressions as well as imperative flow, because in Haskell everything is an expression.

main = do
   putStrLn "Hi, what's your name?"
   userName <- getLine
   if length (words useName) == 2
    then putStrLn "You entered you full name, thanks."
    else error "Please enter both first and last name."

Note that the else is obligatory.

if is actually not used very often in Haskell; guards are more elegant when there are multiple different conditions.

The closest analogue to a C++ if without else (“if cond then do this stuff, else just continue”) is when, which is not a keyword but just a combinator defined in a library.

I don't think you can compare them, as you are comparing a construct of an imperative programming language (C++) with that of an functional programming language (Haskell).

Also it very much depends on the compilers, and how they optimize the code in the first place.

Hmm. case-of is closest in meaning.

Multiple function definitions will generally compile to the same code as a case expression. Guards tend to compile to the same code as an if.

But these two languages are very different. Performance tuning in Haskell programs doesn't look anything like what you'd do in C++.

Related