How do I use "<0" condition in Haskell case

Viewed 338

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.

2 Answers

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 -> ...

You can work with a guard, for example:

factorial x
  | x < 0 = -1
factorial 0 = 0
-- ⋮

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
-- ⋮

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

{-# LANGUAGE ViewPatterns #-}

factorial x = case x of
  ((< 0) -> True) -> -1
  0 -> 1
  -- ⋮
Related