16

Suppose I have a lambda expression in my program like:

\x -> f $ x + 1

and I want to specify for type safety that x must be an Integer. Something like:

-- WARNING: bad code
\x::Int -> f $ x + 1
3
  • 2
    (\x -> f $ (x::Int) + 1) Jan 26, 2013 at 19:34
  • What exactly do you mean by "for type safety"? In what way would the inferred type for x (Num a => a) be less safe than Int?
    – sepp2k
    Jan 26, 2013 at 19:41
  • 2
    @sepp2k The actual code I'm writing does show x, and a lot of things can be shown, but I only want this lambda to compile if x is of a certain type, like Int. The code in the question is not the actual code, it's just the shortest way to ask the question. Jan 26, 2013 at 19:46

2 Answers 2

17

You can just write \x -> f $ (x::Int) + 1 instead. Or, perhaps more readable, \x -> f (x + 1 :: Int). Note that type signatures generally encompass everything to their left, as far left as makes syntactic sense, which is the opposite of lambdas extending to the right.

The GHC extension ScopedTypeVariables incidentally allows writing signatures directly in patterns, which would allow \(x::Int) -> f $ x + 1. But that extension also adds a bunch of other stuff you might not want to worry about; I wouldn't turn it on just for a syntactic nicety.

2
  • 1
    Thanks, great answer. I'm actually using this in Template Haskell, and just FYI regarding the second option, GHC 7.4.1 says "Type signatures in patterns not (yet) handled by Template Haskell". Jan 26, 2013 at 19:44
  • 2
    Haha, yeah. TH doesn't understand quite a few syntactic extensions that GHC supports, alas. Jan 26, 2013 at 20:16
13

I want to add to C.A.McCann's answer by noting that you don't need ScopedTypeVariables. Even if you never use the variable, you can always still do:

\x -> let _ = (x :: T) in someExpressionThatDoesNotUseX

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.