Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The read function in Haskell

Tags:

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.

like image 598
Vaduva Mihaita Bogdan Avatar asked Apr 08 '26 20:04

Vaduva Mihaita Bogdan


2 Answers

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.

like image 80
Ian Henry Avatar answered Apr 10 '26 21:04

Ian Henry


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
like image 24
Random Dev Avatar answered Apr 10 '26 22:04

Random Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!