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?
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With