Search code examples
haskellprogram-entry-point

Main not compiling due to foldr


I've added this code to f.hs file :

main = foldr (+) (0) [1,2,3]

when I use :

:l f.hs

I receive error :

[1 of 1] Compiling Main             ( f.hs, interpreted )

f.hs:1:14:
    No instance for (Num (IO t0)) arising from a use of ‘+’
    In the first argument of ‘foldr’, namely ‘(+)’
    In the expression: foldr (+) (0) [1, 2, 3]
    In an equation for ‘main’: main = foldr (+) (0) [1, 2, 3]
Failed, modules loaded: none.

I want to use trace and see output of fold.

Why is this code not compiling ?


Solution

  • main has type IO () while foldr (+) (0) [1,2,3] has type Num a => a. GHC tries to combine these but fails, since Num is not defined on IO a. Presumably, you want to print the result. Try this

    main = print $ foldr (+) (0) [1,2,3]
    

    Then, once you load into GHCi, you can call main to get 6.