Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell type signature in lambda expression

Tags:

haskell

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
like image 599
Marton Trencseni Avatar asked Jan 26 '13 19:01

Marton Trencseni


People also ask

What is Haskell type signature?

From HaskellWiki. A type signature is a line like. inc :: Num a => a -> a. that tells, what is the type of a variable. In the example inc is the variable, Num a => is the context and a -> a is its type, namely a function type with the kind * -> * .

What is Lambda Haskell?

λ-expressions (λ is the small Greek letter lambda) are a convenient way to easily create anonymous functions — functions that are not named and can therefore not be called out of context — that can be passed as parameters to higher order functions like map, zip etc.


2 Answers

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.

like image 136
C. A. McCann Avatar answered Sep 21 '22 17:09

C. A. McCann


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
like image 33
Gabriella Gonzalez Avatar answered Sep 17 '22 17:09

Gabriella Gonzalez