2

I am new to Haskell and programming in general. I am trying to write a lambda function that return a value squared

(\x  -> x * x) 

this is the code I have written. When i try to compile I get this error Parse error: naked expression at top level Perhaps you intended to use TemplateHaskell

I have googled it I cannot fund a solution

5
  • You should assign this to a function, for example square = \x -> x * x. Commented Jun 25, 2021 at 11:34
  • Thanks that works run if I want to print this I used this code Commented Jun 25, 2021 at 11:39
  • 'printsquare = putStrLn (square(5))' but I get an error Commented Jun 25, 2021 at 11:39
  • 1
    because 25 is not a string. Commented Jun 25, 2021 at 11:39
  • You convert it t a string with putStrLn (show (square 5)) Commented Jun 25, 2021 at 11:40

1 Answer 1

1

You should assign this to a identifier, since \x -> x * x as program does not make much sense: you define a function, but then you throw that function away.

You thus can implement a function:

mysquare :: Num a => a -> a
mysquare = \x -> x * x

then you can call the function when necessary. We can for example define a main with:

main :: IO ()
main = putStrLn (show (mysquare 5))

and then call main:

Prelude> main
25
Sign up to request clarification or add additional context in comments.

5 Comments

printsquare = putStrLn (show (mysquare 5)) does not print anything to the console ?
@KLawson: you defined a function, you did not call that function.
I am confused because I am new to haskell. I already tried this putStrLn (show (mysquare 5)) I get an 'errorParse error: naked expression at top level Perhaps you intended to use TemplateHaskell'. with the previous code it runs but it doesn't output anything
@KLawson: you should assign it to the main to start the program at that point, so main = putStrLn (show (mysquare 5)), then compile and run the compiled program.
Thank you this makes sense. And it actually helped to understand how Haskell works a bit better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.