Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore a polymorph readable type, while reading?

Tags:

haskell

I have a problem similar to:

data Foo a = Foo { myInt :: Integer, myValue :: a } deriving Read

bar :: String -> Integer
bar = myInt . read

main = print $ bar stringWithFooOfa

i don't want to use something like read . (!!1) . words, if i don't need to.

like image 673
Vektorweg Avatar asked Jan 27 '26 11:01

Vektorweg


1 Answers

Add a type annotation to read. As commenters suggested, Haskell has no way of knowing what you're trying to read since you immediately turn it into an Int. To be more clear, consider this example:

data Foo a  = Foo { myInt  :: Integer, myValue  :: a } deriving Read
data Foo2 a = Foo { myInt2 :: Integer                } deriving Read

bar :: String -> Integer
bar = myInt . read

Now there are two very different behaviors for bar possible and it's hard to know which is correct.

To tell Haskell which one you want, use an inline annotation around read:

bar :: String -> Integer
bar = myInt . (read :: String -> Foo ())

Notice that I pick an a, too. Otherwise, we'll be in the same boat as above but just with a instead of Foo.

like image 185
J. Abrahamson Avatar answered Jan 28 '26 23:01

J. Abrahamson



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!