3

Suppose I wanted to test that both my inputs are positive. Can I do something like this?

test :: Float -> Float -> Maybe Float Float 
test a b
    | a>0 && b>0 = a b
    | otherwise = Nothing

I thought I would have this function test that the inputs for the next function were positive. So two floats go in and two come out.

What's an alternative to this?

  • 1
    "It doesn't work" is not a problem statement. Specify the exact error message you are getting. Note that your question may be more suitable on Stack Overflow, it being a question about writing specific code. In English, I is always capitalized. – Robert Harvey Mar 14 '16 at 18:42
  • Note that the Maybe constructor only takes one type. If you want two, you're going to have to pair the Floats some way. Sadly, I'm not that familiar with Haskell to point you towards how to do that. – Telastyn Mar 14 '16 at 18:47
  • Sorry, my English is not mothers tongue. – JJ chips Mar 14 '16 at 18:48
  • 1
    @JJchips you may find running your posts through spellcheckplus.com to be helpful. While it can have difficulty with some technical jargon, it often does a good job of identifying issues. – user40980 Mar 14 '16 at 18:53
8

The code is morally correct but lacking in a few places. The conditional stuff is actually fine, the part that's tripping you up is

  1. Indicating that you want a tuple
  2. Constructing a Maybe value

First of all, the type Maybe Float Float is ill-formed, Maybe takes one type argument not two, I think you mean Maybe (Float, Float) which should be read as "A Maybe of a pair of floats". Then to construct a single expression of type (Float, Float) we use (-, -). So instead of a b which really means "a applied as a function to b" we'd have (a, b), a pair of a and b. Last but not least, we want to construct a Maybe in the end so we need to explicitly wrap the whole tuple in the Just constructor leaving us with Just (a, b).

test :: Float -> Float -> Maybe (Float, Float) 
test a b
    | a>0 && b>0 = Just (a, b)
    | otherwise = Nothing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.