Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a string or an Int depending on input

How do I write a function that takes as input an Int and returns that Int if it is > 0 or otherwise return a dash "-" if it is < 0. I understand that Haskell is strict with its types, but is there a way around this?

like image 486
matt Avatar asked May 28 '26 18:05

matt


2 Answers

Haskell is statically typed meaning that normally you cannot change the type depending on runtime content.

You can however use the Either type:

fun :: Int -> Either Int String
fun x | x > 0 = Left x
      | otherwise = Right "-"

Either is defined as:

data Either a b = Left a | Right b

You can then later in your program query whether you are dealing with the left constructor or the right constructor.

like image 130
Willem Van Onsem Avatar answered May 30 '26 13:05

Willem Van Onsem


I think the Haskell way of doing this would be using Maybe.

positive :: Int -> Maybe Int
positive x | x >= 0 = Just x
           | x < 0  = Nothing

Then, you can pattern match to see if you got a Just or a Nothing. Otherwise, there is no way of writing a function that does what you say - what would its signature be: Int -> Int or Int -> String?

like image 44
Alec Avatar answered May 30 '26 15:05

Alec