beardc
beardc

Reputation: 21073

Haskell function to cast as a type

If I want a version of reads that returns a list of (Int, String), the example I see is

f x = reads x :: [(Int,String)]

I'd like to know if there's a way to do this in point-free style (f = g . reads?), or if this is something you just don't/can't do in Haskell.

I haven't seen any examples of using a type as an argument, so it may not be doable.

Upvotes: 5

Views: 213

Answers (4)

Cubic
Cubic

Reputation: 15703

Yes, there is actually.

fixIS :: [(Int,String)] -> [(Int,String)]
fixIS = id

I usually have a couple of functions lying around for when I want to resolve polymorphis (i.e. when I want to fix the inhibition monoid of a Netwire wire to (), or if I want to fix a Num a to Int). Obviously there's no point in doing this if you only need that once. The reason you might wanna do it this way is that it occasionally flows better in function definitions. Depending on how smart your haskell compiler is it might be less efficient though (in theory, the id could be dropped in most situations... not sure if GHC actively looks for that if id is given another name though).

Upvotes: 0

augustss
augustss

Reputation: 23014

There is currently no way, but I have a suggested language extension, SignatureSections, which will allow you to write f = (:: [(Int, String)]) . reads.

Upvotes: 3

Dan
Dan

Reputation: 13190

The idiomatic way to do what you're describing is

f :: String -> [(Int, String)]
f = reads

The benefit to doing it this way is if you have a polymorphic type the result is what you'd expect (because of the Dreaded Monomorphism Restriction).

Upvotes: 6

Ethan Lynn
Ethan Lynn

Reputation: 1009

I think what you're looking for is f = reads :: String -> [(Int, String)].

Upvotes: 6

Related Questions