3

I am new to the Haskell language and I having some issues with the read function. Precisely, I understand that:

read "8.2" + 3.8

Should return 12.0 because we want to return the same type as the second member. The thing that I don't really get is why does:

read "True" || False

Return True ? Ok, it returned the same type as False, which is Boolean, but what I don't understand is why the first member. I think I have a vague idea, like, the return function in this case will return the first member because the condition is || ? Please help me out. Also, I am sorry if this is just basic for most of you guys, but I really want to undersand it.

3
  • 1
    well True OR anything is True ;) ... (it does not return the first member but the result of the or-operation - try read "True" && False if you like) Commented Apr 21, 2016 at 17:35
  • Thank you! I had the same thought, just needed someone to clarify this for me. Thank you again. Commented Apr 21, 2016 at 17:37
  • np - I guess it's as good as an answer as there could be(?) Commented Apr 21, 2016 at 17:37

2 Answers 2

11

Follow along in ghci!

Prelude> let x = read "True"
Prelude> :t x
x :: Read a => a

So x doesn't have a concrete type. x is sort of an expression that can provide a value of a concrete type, when we ask for it. We could ask x to be an Int or a Bool or anything we want. In particular:

Prelude> x :: Bool
True

We could also ask it to be an Int:

Prelude> x :: Int
*** Exception: Prelude.read: no parse

But it fails to become one.

So in your code snippet, when did we ask it to become something?

Prelude> :t (||)
(||) :: Bool -> Bool -> Bool

The function (||) expects a Bool, so it asks its arguments to become Bools. And as we already saw, when we ask x to become a Bool, it becomes the Bool value True. So saying:

Prelude> x || False
True

Is just like saying:

Prelude> True || False
True

And (||) represents the logical OR operation, so the result is True.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I appreciate your help a lot!
4

well True OR anything is True

it does not return the first member but the result of the or-operation

you should try

read "True" && False

to see the difference


maybe a slight remark/addition:

In a sense you where right that it returns the first component - but only because True || _ = True so even True || undefined is ok:

Prelude> read "True" || undefined
True

1 Comment

Oh, ok, I had it all wrong about the read function. Thank you, again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.