[Haskell-beginners] Identical function and variable names and type inference

Magnus Therning magnus at therning.org
Wed Sep 2 17:42:45 EDT 2009


On Wed, Sep 2, 2009 at 11:24 PM, aditya siram<aditya.siram at gmail.com> wrote:
> Hi all,
> Recently I wrote a function that takes a unique identifier that I called
> 'id'. I then tried to apply the 'id' function to it and GHC did not like
> that. But it should.
>
> For example in 'test' I have told the compiler that the id argument is an
> Int. So type inference should be able to determine the first 'id' in 'id id'
> couldn't possibly be an Int, but it complains. So I explicitly told the
> compiler the type of 'id' in test1 - this didn't work either. The final
> function 'test3' works as expected. Is there something I am not understand
> about the way type inference is supposed to work?
>
> test :: Int -> Int
> test id = id id
>
> test1 :: Int -> Int
> test1 id = idFunc id
>     where
>       idFunc :: a -> a
>       idFunc = id
>
> test2 :: Int -> Int
> test2 myid at id = id myid
>
> test3 :: Int -> Int
> test3 id = Prelude.id id

How is the compiler supposed to differentiate between the situation
where you really mean `id id` (and it type checks properly) and where
you've mistakenly written `id id` (but it doesn't type check)?

If that doesn't make you realise then think of it as your `id`
shadowing the Prelude's, and that happens irrespective of the types.

/M

-- 
Magnus Therning                        (OpenPGP: 0xAB4DFBA4)
magnus@therning.org          Jabber: magnus@therning.org
http://therning.org/magnus         identi.ca|twitter: magthe


More information about the Beginners mailing list