whd
whd

Reputation: 1861

Haskell type dessignation

I have to dessignate types of 2 functions(without using compiler :t) i just dont know how soudl i read these functions to make correct steps.

f x = map -1 x
f x = map (-1) x

Well i'm a bit confuse how it will be parsed

Upvotes: 3

Views: 115

Answers (4)

whd
whd

Reputation: 1861

well i did it by my self :P

(map) - (1 x)
(-)::Num a => a->a->->a
1::Num b=> b
x::e
map::(c->d)->[c]->[d]
map::a
a\(c->d)->[c]->[d]
(1 x)::a
1::e->a
f::(Num ((c->d)->[c]->[d]),Num (e->(c->d)->[c]->[d])) => e->(c->d)->[c]->[d]

Upvotes: 0

hammar
hammar

Reputation: 139870

Function application, or "the empty space operator" has higher precedence than any operator symbol, so the first line parses as f x = map - (1 x), which will most likely1 be a type error.

The other example is parenthesized the way it looks, but note that (-1) desugars as negate 1. This is an exception from the normal rule, where operator sections like (+1) desugar as (\x -> x + 1), so this will also likely1 be a type error since map expects a function, not a number, as its first argument.

1 I say likely because it is technically possible to provide Num instances for functions which may allow this to type check.

Upvotes: 4

dflemstr
dflemstr

Reputation: 26167

These functions do not have types, because they do not type check (you will get ridiculous type class constraints). To figure out why, you need to know that (-1) has type Num n => n, and you need to read up on how a - is interpreted with or without parens before it.

The following function is the "correct" version of your function:

f x = map (subtract 1) x

You should be able to figure out the type of this function, if I say that:

subtract 1 :: Num n => n -> n
map :: (a -> b) -> [a] -> [b]

Upvotes: 2

John L
John L

Reputation: 28097

For questions like this, the definitive answer is to check the Haskell Report. The relevant syntax hasn't changed from Haskell 98.

In particular, check the section on "Expressions". That should explain how expressions are parsed, operator precedence, and the like.

Upvotes: 3

Related Questions