Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composition with lambda expressions haskell

I try a dummy example of using composition with lambda expression. The below code compile, but it doesn't run when I try (f.g) 3 2

f x = x^2
g x = 5*x

f.g = \x -> f(g x)
    

It gives such an error:

Ambiguous occurrence `.'
It could refer to
   either `Prelude..',
          imported from `Prelude' at list3.hs:1:1
          (and originally defined in `GHC.Base')
       or `Main..', defined at list3.hs:42:3.

Can somebody please tell me where is the problem?

like image 414
xmathx Avatar asked Dec 30 '25 16:12

xmathx


1 Answers

You defined a composition operator that exists along side the one imported from the Prelude. There's nothing wrong with the definition; the problem occurs when you try to use it, as the compiler can't tell if something like

main = print $ f . g $ 10

is supposed to use . from the Prelude or . from your Main module.

One solution is to simply be explicit about which of the two you want.

f . g = \x -> f (g x)

main = print $ f Main.. g $ 10

or to not import the Prelude version in the first place.

{-# LANGUAGE NoImplicitPrelude #-}

import Prelude hiding ((.))

-- Now this is the *only* definition.
f . g = \x -> f (g x)

main = print $ f . g $ 10
like image 55
chepner Avatar answered Jan 01 '26 09:01

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!