Unexpected if expression in function application [GHC-01239]
Unlike in many other languages, in Haskell the If-Then-Else construct is an expression, which means it returns a value that can be processed further.
ageMessage :: Int -> String
= if age < 18 then "You are too young to enter" else "Welcome to the club"
ageMessage age
putStrLn (ageMessage 10) -- You are too young to enter
putStrLn (ageMessage 20) -- Welcome to the club
Because If-Then-Else expressions return values, it makes sense to pass them as input to a function. However, without language extensions, Haskell’s grammar requires parentheses around them in function argument positions.
Examples
Unexpected if expression in function application
To pass If-Then-Else expressions as function arguments we either have to surround them in parentheses,
use the function application operator ($)
or enable the BlockArguments
extension.
Error Message
IfInFunAppExpr.hs:4:18: error:
Unexpected if expression in function application:
if True then [1] else []
Suggested fixes:
• Use parentheses.
• Perhaps you intended to use BlockArguments
|
4 | example = length if True then [1] else []
| ^^^^^^^^^^^^^^^^^^^^^^^^
IfInFunAppExpr.hs
Before
module IfInFunAppExpr where
example :: Int
example = length if True then [1] else []
After
{-# LANGUAGE BlockArguments #-}
module IfInFunAppExpr where
-- Requires BlockArguments language extension to work
example :: Int
example = length if True then [1] else []
-- Works without BlockArguments
example2 :: Int
example2 = length (if True then [1] else [])
-- Works without BlockArguments
example3 :: Int
example3 = length $ if True then [1] else []