2

So i am trying to make a recursive factorial function using the case expression and if else although I don't know how to write the <0 condition for my code

factorial x = case of x
                      <0 -> -1
                       0 ->  0
                          .
                          .
                          .
   

I am completely new to Haskell so please don't be too harsh on me.

Will Ness
  • 70,110
  • 9
  • 98
  • 181
m3k_1
  • 383
  • 4
  • 15

2 Answers2

4

case takes an arbitrary expression, not just a single variable, so you could write something like

factorial x = case compare x 0 of
               LT -> -1
               EQ -> 1
               GT -> ...
chepner
  • 497,756
  • 71
  • 530
  • 681
1

You can work with a guard, for example:

factorial x
  | x < 0 = -1
factorial 0 = 0
-- &vellip;

or we can add these guards to the case statement, as @Dan D. says:

factorial x = case x of
  x | x < 0 -> -1
  0 -> 0
-- &vellip;

or you can work with view patterns [Haskell gitlab wiki]:

{-# LANGUAGE ViewPatterns #-}

factorial x = case x of
  ((< 0) -> True) -> -1
  0 -> 1
  -- &vellip;
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Are not guards supported in case expressions as https://stackoverflow.com/a/40836465 shows? – Dan D. May 13 '21 at 08:28
  • @DanD.: yes indeed. Somehow I find it a bit ugly however since we use the `x` variable *four* times: one in the head of the function definition, one in the `case ... of`, one in the pattern, and one in the guard. – Willem Van Onsem May 13 '21 at 08:31
  • pretty intricate way to write `case (x < 0) of True -> ...` or just `if (x < 0) then ....`. :) – Will Ness May 13 '21 at 12:17