Vaduva Mihaita Bogdan
Vaduva Mihaita Bogdan

Reputation: 170

The read function in Haskell

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.

Upvotes: 3

Views: 2377

Answers (2)

Ian Henry
Ian Henry

Reputation: 22403

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.

Upvotes: 11

Random Dev
Random Dev

Reputation: 52270

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

Upvotes: 4

Related Questions