简体   繁体   中英

What is the “::” equivalent function in Haskell?

In Python, we have a built-in package, named "operator", with which we can use function version of any operator. It is highly used when using "functional Programming" functions like map and reduce, and is much better recommended than using "lambda".

I have the same problem in Haskell: I want t user mapM somewhere with a composition of many functions but I have to use not-so-pretty lambda:

mapM ((\x->x::String).fromSql.(!!1)) res

Is there any equivalent to that liek this:

mapM (someFunc(String).fromSql.(!!1)) res

::String is not an operator in the sense of python's string(…) , but a type annotation, and as such, special syntactic rules apply.

You can, however, define function

asString :: String -> String
asString x = x

and then write

mapM (asString.fromSql.(!!1)) res

@augustss once proposed a language extension that would allow (::String) to be used, but I cannot find it right now.)

As chepner commented, it really shouldn't be necessary to give any type hint at all: all you need is

   mapM (fromSql . (!!1)) res

...that is, provided you actually use the result in some way. (If you don't use the result, then why do you do this in the first place?)

The reason being: unlike Python, Haskell has a proper Hindley-Milner type system, and this can infer types in any direction and any context. So if you write just, for instance,

 do
   sqlStrs <- mapM (fromSql . (!!1)) res
   ...
   mapM_ putStrLn sqlStr

then this is enough for the compiler to infer that sqlStrs :: [String] and hence fromSql must be restricted to yield String .


There are some exceptions, but these arise only with the monomorphism restriction (which only applies to global definitions, not to something bound in a monad, and can also be turned off) or when using extensions like GADTs, ExistentialQuantification or RankNTypes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM