Haskell parse error on input import

Oh, The Kinds of Errors You’ll See 26 Jul 2018 Oh, The Kinds of Errors You’ll See Haskell has what I would consider to be 3 different types of errors: parse errors, definition errors, & type errors. Parse errors occur when we have broken a formatting rule or some convention enforced by the compiler. […]

Содержание

  1. Oh, The Kinds of Errors You’ll See
  2. 26 Jul 2018
  3. Oh, The Kinds of Errors You’ll See
  4. Error #1
  5. Top Of File
  6. Fix #1 Order Matters
  7. Error #2
  8. Indentation Rules
  9. Fix #2
  10. Indentation Fixed
  11. Error #3
  12. Functions are Top Level Declarations
  13. Fix #3
  14. Functions at The Top Level
  15. Error #4
  16. Type signatures for functions that exist
  17. Error #5
  18. module Main where
  19. Fix #5 main for Main
  20. Error #6
  21. main :: IO Type
  22. Fix #6 IO & main, together forever
  23. Properly formatted file!
  24. Ошибка синтаксического анализа ошибок Haskell при вводе `= ‘
  25. 4 ответы

Oh, The Kinds of Errors You’ll See

26 Jul 2018

Oh, The Kinds of Errors You’ll See

Haskell has what I would consider to be 3 different types of errors: parse errors, definition errors, & type errors.

Parse errors occur when we have broken a formatting rule or some convention enforced by the compiler.

Once we fix all of those we will get definition errors. Definition errors occur when we are calling that function that isn’t defined by us in our scope or the function hasn’t been imported from another module.

Once we fix all our definition errors we’ll get type errors. Type errors occur when we told the compiler we would do something via our types & we haven’t followed through in our function. After you fix all those errors you’ll get your program to run!

We’re going to step through fixing a file that has various parse errors & then, at the end, have a file that compiles correctly. If you would like to follow along in your own REPL you can find the code here.

Here we have a file that’s breaking some formatting rules. Let’s try compiling this & see what error messages we get.

Error #1

Our first error upon loading the module is a parse error on input module . This error occurred on line 5 of our file. Let’s go look at it.

Top Of File

The rules, for what the top of Haskell files should look, are:

  • Language pragmas are listed at the top of the file
  • Module name is declared above imports & code
  • Imported modules listed before functions

I personally like to have LANGUAGE in all uppercase because I like to yell as much as possible in my code. If you decide to give your file a module name, it must be above the imported modules & functions, with a capitalized name. Then you list modules you would like to import into your file. Imported modules must come before your functions.

Fix #1 Order Matters

Here we’ve moved module Main where above our imported module. Let’s reload to see our next error.

Error #2

The compiler tells us that we have a parse error on input right arrow. It shows us that the error in on line 14. Let’s go check out the code.

The error is on the line that starts with False , line 14. But there are a couple of other problems in the ruleBreaker & lie function too. So keep in mind the where block & the let for the rules we discuss next.

Indentation Rules

For this section, I’m assuming you’re using spaces & using whitespace to denote separation of code blocks. There are warnings by default in Haskell if you use tabs. You can also use curly braces in your code to denote separate blocks. Spaces & whitespace are my preference in Haskell because I think it makes my code look nice. 🙂

  • Code implementations start at least 1 space after the function name on the following line

My most common error is not having enough spaces between my function name & my implementation on the next line. You need to have the implementation 1 space over on the next line compared to the function name. This rule applies for let in expressions, case of expressions, guards, & where blocks!

  • New code blocks inside of other functions must be 1 space over to denote a new block

When you start a new block you need to indent those expressions by at least 1 space. Most people will use at least 2 spaces for readability. So here we can see that we need a new code block because of the use of a case of expression. If you’re using a control structure & the following code will be on a new line that’s a pretty good indication you will need to indent your next section.

  • Code blocks must spatially align

Our True & False here are in the same block because they’re both values our case b of can reduce to. Because these expressions are in the same block we need to make sure that they line up.

Fix #2

Here is our fixed indentation!

Below is our code that wasn’t following our indentation rules.

Indentation Fixed

We fixed all our indentation problems by following the rules we just talked about! Let’s reload the file & see where we’re at with this file now.

Error #3

Parse error. Possibly incorrect indentation. I know what you’re thinking.

You said we fixed all our indentation!

I promise I didn’t lie.

This error occurs on line 19 & we don’t have a line 19 in our file! Let’s go look at the end of the file instead.

Why doesn’t this work? Well, let’s look at the rule.

Functions are Top Level Declarations

let & where are meant to define functions inside other functions to a local scope.

Just a function name at the top level will be fine!

We can’t have anything but functions at the top level of our file. You might be use to declaring things that look like variables using an identifier to distinguish it from functions, but in Haskell everything is a function!

Fix #3

Here is the fixed version of our lie function.

Here is the old version that didn’t compile.

Functions at The Top Level

We got rid of our let here & now let’s recompile.

Error #4

We’ve moved onto definition errors now! We won’t see any more parse errors now! When you get to this stage in your own files you can congratulate yourself on making through 1 stage of the compilation process. 🙂

The type signature for ruleBreaker doesn’t have a function associated with it. Let’s go look at line 10 of our file.

The type signature & the function name are different. You may notice that there is a typo in one of them.

If you have a type signature, you must have a function implementation with it. We’ll just fix our typo.

Type signatures for functions that exist

We fixed our typo & now let’s reload our code!

Error #5

The next error we get here says that the function main isn’t found in our module Main . Let’s look at the code & see if that’s true.

We can see in the code that we have a module Main on line 3 & we don’t have a function called main anywhere in our file. Instead we have a function called mymain .

module Main where

The rule we’re breaking here is that if you use module Main you have to have a function called main . If for whatever reason you don’t want to have a main function, just name your module anything else (that starts with a capital letter).

Fix #5 main for Main

So we will rename mymain to main & reload our code to see how we’re doing.

Error #6

We fixed the definition errors we got & now we’ve gotten some type errors!

Really this is 2 errors, but they go really well hand in hand. The first error says we couldn’t match the expected type of main , which is IO of something, with the actual type, in the type signature, Int . The compiler tells us on the 2nd error that we told them we would give them an Int , but we are actually providing an IO () . It points to line 8, specifically at the expression: print «hello world» . This is expected because print has the type is a to IO () where a has the constraint to have an instance of Show . Let’s go look at those lines.

We did in fact say we would return an Int here & we aren’t doing it.

main :: IO Type

main always returns IO of some type. Usually main gives us back a value of IO ()

In our main function we use print . print has the type a to IO () . So we know we’ll want to return IO () .

The rule for using the function main is that main must return IO of some type. It doesn’t have to be IO () , but print has the return type of IO () . Let’s change our type signature of main to IO () .

Fix #6 IO & main, together forever

Here we are, main has the type IO () , which reflects the type that print «hello world» gives us. Let’s reload.

Sweet! Our file is properly formatted now! There are no more errors in our code & this will run fine. So… just one more thing. 🙂

Properly formatted file!

Let’s change the strings to reflect that our code compiles haha.

If you notice any issues with this post please submit an issue here. If this was easy for you to follow along with please consider adding to the Haskell wiki on compiler errors.

Источник

Ошибка синтаксического анализа ошибок Haskell при вводе `= ‘

Я новичок в Haskell, и после запуска ghci Я пытался:

чего я не понимаю.

Как ни странно, раньше это работало хорошо. Я полагаю, что я неправильно сконфигурировал Haskell. Переустановка ghc6 не решает проблемы.

Для информации я использую Ubuntu 10.4, а версия ghc6 — 6.12.1-12.

задан 31 мая ’11, 05:05

4 ответы

В GHCi 7.x или ниже вам понадобится let определять вещи в нем.

Начиная с GHC 8.0.1, привязки верхнего уровня поддерживаются в GHCi, поэтому код OP будет работать без изменений.

Спасибо. «Real world haskell» (по крайней мере, в моей версии) не имеет let в своих примерах — Михей

@Бакуриу LYAH делает теперь упомяните let . Но продолжение. В LYAH Я читаю addThree :: Int -> Int -> Int -> Int (новая линия) addThree x y z = x + y + z но только второй вбегает GHCi с let . Почему? — изоморфизмы

@Bakuriu Да, но автор советует вам записывать свои определения во внешний файл и загружать его в GHCI, а не записывать их непосредственно в GHCI. И первое работает отлично. — суперзамп

Тогда это руководство совершенно неверно: Seas.upenn.edu/

cis194/lectures/01-intro.html . Тем не менее, это первое руководство, рекомендованное на сайте haskell! — Cammil

Когда вы вводите исходный файл Haskell,

Когда вы вводите непосредственно в ghci, вам нужно вводить let в начале строки:

ответ дан 31 мая ’11, 09:05

Почему не работает в GHCi? Почему есть разница в синтаксисе? — Бить

@Beat GHCi пытается оценивать выражения по умолчанию, а не синтаксический анализ операторов, тогда как формат файла противоположный. Вот почему, чтобы делать утверждения (например, устанавливать переменные, определять функции и т. Д.), Вы должны объявить, что вы используете let . Думайте о GHCi как о большом let . in . утверждение. — АЖФ

Хорошее практическое правило использования ghci заключается в том, что любой вводимый вами код должен соответствовать семантике do-block; то есть вы могли предположить синтаксически что вы программируете в монаде ввода-вывода (если это новая терминология, не волнуйтесь! Я настоятельно рекомендую прочитать это учебник).

Эта медитация Ответ иллюстрирует этот момент на примере и может дать более подробное представление о природе ввода-вывода и ghci.

ответ дан 23 мая ’17, 13:05

Этот ответ бесполезен для новичка. Он ищет простой действенный совет, чтобы двигаться вперед, а не сложные темы. Вы не объясняете полиномиальные произведения ребенку, изучающему таблицу умножения — она ​​не показывает, сколько вы знаете, это показывает, что вы не знаете, как поделиться тем, что вы знаете. — БТК

@btk: в какой-то момент каждый должен перестать быть новичком. Я начал изучать Haskell вчера и уверен, что через короткое время я пойму все, что говорит Раиз. — Вьетни Фуван

Это мой первый день изучения Haskell, и я нашел этот ответ очень полезным для понимания того, почему я должен использовать let ; Я подумал: «Черт возьми, зачем мне использовать let «а потом я прочитал это и был просветлен. — Брайан Тингл

Начиная с GHC 8.0.1 это больше не будет генерировать ошибку.

Источник

Click here follow the steps to fix Parse Error On Input Import Haskell and related errors.

Instructions

 

To Fix (Parse Error On Input Import Haskell) error you need to
follow the steps below:

Step 1:

 
Download
(Parse Error On Input Import Haskell) Repair Tool
   

Step 2:

 
Click the «Scan» button
   

Step 3:

 
Click ‘Fix All‘ and you’re done!
 

Compatibility:
Windows 7, 8, Vista, XP

Download Size: 6MB
Requirements: 300 MHz Processor, 256 MB Ram, 22 MB HDD

Limitations:
This download is a free evaluation version. To unlock all features and tools, a purchase is required.

Parse Error On Input Import Haskell Error Codes are caused in one way or another by misconfigured system files
in your windows operating system.

If you have Parse Error On Input Import Haskell errors then we strongly recommend that you

Download (Parse Error On Input Import Haskell) Repair Tool.

This article contains information that shows you how to fix
Parse Error On Input Import Haskell
both
(manually) and (automatically) , In addition, this article will help you troubleshoot some common error messages related to Parse Error On Input Import Haskell error code that you may receive.

Note:
This article was updated on 2023-02-03 and previously published under WIKI_Q210794

Contents

  •   1. What is Parse Error On Input Import Haskell error?
  •   2. What causes Parse Error On Input Import Haskell error?
  •   3. How to easily fix Parse Error On Input Import Haskell errors

What is Parse Error On Input Import Haskell error?

The Parse Error On Input Import Haskell error is the Hexadecimal format of the error caused. This is common error code format used by windows and other windows compatible software and driver vendors.

This code is used by the vendor to identify the error caused. This Parse Error On Input Import Haskell error code has a numeric error number and a technical description. In some cases the error may have more parameters in Parse Error On Input Import Haskell format .This additional hexadecimal code are the address of the memory locations where the instruction(s) was loaded at the time of the error.

What causes Parse Error On Input Import Haskell error?

The Parse Error On Input Import Haskell error may be caused by windows system files damage. The corrupted system files entries can be a real threat to the well being of your computer.

There can be many events which may have resulted in the system files errors. An incomplete installation, an incomplete uninstall, improper deletion of applications or hardware. It can also be caused if your computer is recovered from a virus or adware/spyware
attack or by an improper shutdown of the computer. All the above actives
may result in the deletion or corruption of the entries in the windows
system files. This corrupted system file will lead to the missing and wrongly
linked information and files needed for the proper working of the
application.

How to easily fix Parse Error On Input Import Haskell error?

There are two (2) ways to fix Parse Error On Input Import Haskell Error:

Advanced Computer User Solution (manual update):

1) Start your computer and log on as an administrator.

2) Click the Start button then select All Programs, Accessories, System Tools, and then click System Restore.

3) In the new window, select «Restore my computer to an earlier time» option and then click Next.

4) Select the most recent system restore point from the «On this list, click a restore point» list, and then click Next.

5) Click Next on the confirmation window.

6) Restarts the computer when the restoration is finished.

Novice Computer User Solution (completely automated):

1) Download (Parse Error On Input Import Haskell) repair utility.

2) Install program and click Scan button.

3) Click the Fix Errors button when scan is completed.

4) Restart your computer.

How does it work?

This tool will scan and diagnose, then repairs, your PC with patent
pending technology that fix your windows operating system registry
structure.
basic features: (repairs system freezing and rebooting issues , start-up customization , browser helper object management , program removal management , live updates , windows structure repair.)

26 Jul 2018

Reading time ~13 minutes

Oh, The Kinds of Errors You’ll See

Haskell has what I would consider to be 3 different types of errors: parse errors, definition errors, & type errors.

Parse errors occur when we have broken a formatting rule or some convention enforced by the compiler.

Once we fix all of those we will get definition errors. Definition errors occur when we are calling that function that isn’t defined by us in our scope or the function hasn’t been imported from another module.

Once we fix all our definition errors we’ll get type errors. Type errors occur when we told the compiler we would do something via our types & we haven’t followed through in our function. After you fix all those errors you’ll get your program to run!

We’re going to step through fixing a file that has various parse errors & then, at the end, have a file that compiles correctly. If you would like to follow along in your own REPL you can find the code here.

Here we have a file that’s breaking some formatting rules. Let’s try compiling this & see what error messages we get.

{-# LANGUAGE InstanceSigs #-}

import Control.Applicative

module Main where

mymain :: Int
mymain = print "hello world"

ruleBreaker :: Bool -> String
rulebraker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
      False -> "no broken rules here... " ++ truth
        where truth = "sorry, that isn't true"

let lie = 
"this code will compile fine"

Error #1

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

format.hs:5:1: error: parse error on input ‘module’
  |
5 | module Main where
  | ^^^^^^
Failed, no modules loaded.

Our first error upon loading the module is a parse error on input module. This error occurred on line 5 of our file. Let’s go look at it.

{-# LANGUAGE InstanceSigs #-}

import Control.Applicative

module Main where
-- ^ `module Main where` is line 5 of our file
mymain :: Int
mymain = print "hello world"

ruleBreaker :: Bool -> String
rulebraker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
      False -> "no broken rules here... " ++ truth
        where truth = "sorry, that isn't true"

let lie = 
"this code will compile fine"

Top Of File

The rules, for what the top of Haskell files should look, are:

  • Language pragmas are listed at the top of the file
  • Module name is declared above imports & code
  • Imported modules listed before functions

I personally like to have LANGUAGE in all uppercase because I like to yell as much as possible in my code. If you decide to give your file a module name, it must be above the imported modules & functions, with a capitalized name. Then you list modules you would like to import into your file. Imported modules must come before your functions.

Fix #1 Order Matters

{-# LANGUAGE InstanceSigs #-}

module Main where

import Control.Applicative

mymain :: Int
mymain = print "hello world"

ruleBreaker :: Bool -> String
rulebraker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
      False -> "no broken rules here... " ++ truth
      where truth = "sorry, that isn't true"

let lie = 
"this code will compile fine"

Here we’ve moved module Main where above our imported module. Let’s reload to see our next error.

Error #2

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

format.hs:14:13: error: parse error on input ‘->’
   |
14 |       False -> "no broken rules here... " ++ truth
   |             ^^
Failed, no modules loaded.

The compiler tells us that we have a parse error on input right arrow. It shows us that the error in on line 14. Let’s go check out the code.

{-# LANGUAGE InstanceSigs #-}

module Main where

import Control.Applicative

mymain :: Int
mymain = print "hello world"

ruleBreaker :: Bool -> String
rulebraker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
      False -> "no broken rules here... " ++ truth
      where truth = "sorry, that isn't true"

let lie = 
"this code will compile fine"

The error is on the line that starts with False, line 14. But there are a couple of other problems in the ruleBreaker & lie function too. So keep in mind the where block & the let for the rules we discuss next.

Indentation Rules

For this section, I’m assuming you’re using spaces & using whitespace to denote separation of code blocks. There are warnings by default in Haskell if you use tabs. You can also use curly braces in your code to denote separate blocks. Spaces & whitespace are my preference in Haskell because I think it makes my code look nice. :)

  • Code implementations start at least 1 space after the function name on the following line
rulebraker b = 
    case b of
        ...

My most common error is not having enough spaces between my function name & my implementation on the next line. You need to have the implementation 1 space over on the next line compared to the function name. This rule applies for let in expressions, case of expressions, guards, & where blocks!

  • New code blocks inside of other functions must be 1 space over to denote a new block
    case b of
      True -> "yeah this code doesn't follow the rules"
      False -> "no broken rules here... " ++ truth

When you start a new block you need to indent those expressions by at least 1 space. Most people will use at least 2 spaces for readability. So here we can see that we need a new code block because of the use of a case of expression. If you’re using a control structure & the following code will be on a new line that’s a pretty good indication you will need to indent your next section.

  • Code blocks must spatially align
rulebraker b = 
    case b of
      True -> "yeah this code doesn't follow the rules"
      False -> "no broken rules here... " ++ truth
        where truth = "sorry, that isn't true"

Our True & False here are in the same block because they’re both values our case b of can reduce to. Because these expressions are in the same block we need to make sure that they line up.

Fix #2

Here is our fixed indentation!

ruleBreaker :: Bool -> String
rulebraker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
    False -> "no broken rules here... " ++ truth
      where truth = "sorry, that isn't true"

let lie = 
     "this code will compile fine"

Below is our code that wasn’t following our indentation rules.

rulebraker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
      False -> "no broken rules here... " ++ truth
      where truth = "sorry, that isn't true"

let lie = 
"this code will compile fine"

Indentation Fixed

{-# LANGUAGE InstanceSigs #-}

module Main where

import Control.Applicative

mymain :: Int
mymain = print "hello world"

ruleBreaker :: Bool -> String
rulebraker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
    False -> "no broken rules here... " ++ truth
      where truth = "sorry, that isn't true"

let lie = 
     "this code will compile fine"

We fixed all our indentation problems by following the rules we just talked about! Let’s reload the file & see where we’re at with this file now.

Error #3

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

format.hs:19:1: error:
    parse error (possibly incorrect indentation or mismatched brackets)
Failed, no modules loaded.

Parse error. Possibly incorrect indentation. I know what you’re thinking.

You said we fixed all our indentation!

I promise I didn’t lie.

This error occurs on line 19 & we don’t have a line 19 in our file! Let’s go look at the end of the file instead.

let lie = 
     "this code will compile fine"

Why doesn’t this work? Well, let’s look at the rule.

Functions are Top Level Declarations

let & where are meant to define functions inside other functions to a local scope.

Just a function name at the top level will be fine!

We can’t have anything but functions at the top level of our file. You might be use to declaring things that look like variables using an identifier to distinguish it from functions, but in Haskell everything is a function!

Fix #3

Here is the fixed version of our lie function.

lie = 
  "this code will compile fine"

Here is the old version that didn’t compile.

let lie = 
     "this code will compile fine"

Functions at The Top Level

{-# LANGUAGE InstanceSigs #-}

module Main where

import Control.Applicative

mymain :: Int
mymain = print "hello world"

ruleBreaker :: Bool -> String
rulebraker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
    False -> "no broken rules here... " ++ truth
      where truth = 
             "sorry, that isn't true"

lie = 
 "this code will compile fine"

We got rid of our let here & now let’s recompile.

Error #4

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

format.hs:10:1: error:
    The type signature for ‘ruleBreaker’ lacks an 
    accompanying binding
   |
10 | ruleBreaker :: Bool -> String
   | ^^^^^^^^^^^
Failed, no modules loaded.

We’ve moved onto definition errors now! We won’t see any more parse errors now! When you get to this stage in your own files you can congratulate yourself on making through 1 stage of the compilation process. :)

The type signature for ruleBreaker doesn’t have a function associated with it. Let’s go look at line 10 of our file.

ruleBreaker :: Bool -> String
rulebraker b = 
  case b of
    ...

The type signature & the function name are different. You may notice that there is a typo in one of them.

If you have a type signature, you must have a function implementation with it. We’ll just fix our typo.

Type signatures for functions that exist

{-# LANGUAGE InstanceSigs #-}

module Main where

import Control.Applicative

mymain :: Int
mymain = print "hello world"

ruleBreaker :: Bool -> String
ruleBreaker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
    False -> "no broken rules here... " ++ truth
      where truth = 
             "sorry, that isn't true"

lie = 
 "this code will compile fine"

We fixed our typo & now let’s reload our code!

Error #5

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

format.hs:1:1: error:
    The IO action ‘main’ is not defined in module ‘Main’
  |
1 | module Main where
  | ^
Failed, no modules loaded.

The next error we get here says that the function main isn’t found in our module Main. Let’s look at the code & see if that’s true.

{-# LANGUAGE InstanceSigs #-}
-- | We have a module called Main
module Main where

import Control.Applicative
-- | We have a function called `mymain`
mymain :: Int
mymain = print "hello world"

We can see in the code that we have a module Main on line 3 & we don’t have a function called main anywhere in our file. Instead we have a function called mymain.

module Main where

The rule we’re breaking here is that if you use module Main you have to have a function called main. If for whatever reason you don’t want to have a main function, just name your module anything else (that starts with a capital letter).

Fix #5 main for Main

{-# LANGUAGE InstanceSigs #-}

module Main where

import Control.Applicative

main :: Int
main = print "hello world"

ruleBreaker :: Bool -> String
ruleBreaker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
    False -> "no broken rules here... " ++ truth
      where truth = 
             "sorry, that isn't true"

lie = 
 "this code will compile fine"

So we will rename mymain to main & reload our code to see how we’re doing.

Error #6

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

format.hs:8:1: error:
    • Couldn't match expected type ‘IO t0’ with actual type ‘Int’
    • In the expression: main
      When checking the type of the IO action ‘main’
   |
 8 | main = print "hello world"
   | ^

format.hs:8:8: error:
    • Couldn't match expected type ‘Int’ with actual type ‘IO ()’
    • In the expression: print "hello world"
      In an equation for ‘main’: main = print "hello world"
   |
 8 | main = print "hello world"
   |        ^^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.

We fixed the definition errors we got & now we’ve gotten some type errors!

Really this is 2 errors, but they go really well hand in hand. The first error says we couldn’t match the expected type of main, which is IO of something, with the actual type, in the type signature, Int. The compiler tells us on the 2nd error that we told them we would give them an Int, but we are actually providing an IO (). It points to line 8, specifically at the expression: print "hello world". This is expected because print has the type is a to IO () where a has the constraint to have an instance of Show. Let’s go look at those lines.

main :: Int
main = print "hello world"

We did in fact say we would return an Int here & we aren’t doing it.

main :: IO Type

main always returns IO of some type. Usually main gives us back a value of IO ()

In our main function we use print. print has the type a to IO (). So we know we’ll want to return IO ().

The rule for using the function main is that main must return IO of some type. It doesn’t have to be IO (), but print has the return type of IO (). Let’s change our type signature of main to IO ().

Fix #6 IO & main, together forever

{-# LANGUAGE InstanceSigs #-}

module Main where

import Control.Applicative

main :: IO ()
main = print "hello world"

ruleBreaker :: Bool -> String
ruleBreaker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
    False -> "no broken rules here... " ++ truth
      where truth = 
             "sorry, that isn't true"

lie = 
 "this code will compile fine"

Here we are, main has the type IO (), which reflects the type that print "hello world" gives us. Let’s reload.

[1 of 1] Compiling Main             ( format.hs, interpreted )
Ok, one module loaded.

Sweet! Our file is properly formatted now! There are no more errors in our code & this will run fine. So… just one more thing. :)

Properly formatted file!

{-# LANGUAGE InstanceSigs #-}

module Main where

import Control.Applicative

main :: IO ()
main = print "hello world"

ruleBreaker :: Bool -> String
ruleBreaker b = 
  case b of
    True -> "yeah this code doesn't follow the rules"
    False -> "no broken rules here... " ++ truth
      where truth = 
             "it's true!"

lie = 
 "this code won't compile fine"

Let’s change the strings to reflect that our code compiles haha.

If you notice any issues with this post please submit an issue here. If this was easy for you to follow along with please consider adding to the Haskell wiki on compiler errors.

Я новичок в Haskell, и после запуска ghci Я пытался:

f x = 2 * x

и я получил:

<interactive>:1:4: parse error on input `='

чего я не понимаю.

Как ни странно, раньше это работало хорошо. Я полагаю, что я неправильно сконфигурировал Haskell. Переустановка ghc6 не решает проблемы.

Для информации я использую Ubuntu 10.4, а версия ghc6 — 6.12.1-12.

4 ответы

В GHCi 7.x или ниже вам понадобится let определять вещи в нем.

Prelude> let f x = x * 2
Prelude> f 4
8

Начиная с GHC 8.0.1, привязки верхнего уровня поддерживаются в GHCi, поэтому код OP будет работать без изменений.

GHCi, version 8.0.1.20161213: http://www.haskell.org/ghc/  :? for help
Prelude> f x = x * 2
Prelude> f 4
8

Создан 11 янв.

Когда вы вводите исходный файл Haskell,

f x = 2 * x

правильно.

Когда вы вводите непосредственно в ghci, вам нужно вводить let в начале строки:

let f x = 2 * x

ответ дан 31 мая ’11, 09:05

Хорошее практическое правило использования ghci заключается в том, что любой вводимый вами код должен соответствовать семантике do-block; то есть вы могли предположить синтаксически что вы программируете в монаде ввода-вывода (если это новая терминология, не волнуйтесь! Я настоятельно рекомендую прочитать это учебник).

Эта медитация Ответ иллюстрирует этот момент на примере и может дать более подробное представление о природе ввода-вывода и ghci.

ответ дан 23 мая ’17, 13:05

Начиная с GHC 8.0.1 это больше не будет генерировать ошибку.

ответ дан 15 окт ’16, 05:10

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

haskell

or задайте свой вопрос.

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

noahlz opened this issue

Jun 29, 2013

· 4 comments


Closed

haskell: parse error on input `=’

#50

noahlz opened this issue

Jun 29, 2013

· 4 comments

Comments

@noahlz

GHCi, version 7.4.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> add a b = a + b

<interactive>:2:9: parse error on input `='

@noahlz



Copy link


Contributor

Author

Is this an issue with running in interactive mode?

@noahlz



Copy link


Contributor

Author

noahlz

added a commit
to noahlz/learnxinyminutes-docs
that referenced
this issue

Jun 29, 2013

@noahlz

@egonSchiele

This is already mentioned at the bottom in the ghci section…maybe we should just move this section to the top?

@noahlz



Copy link


Contributor

Author

Agreed that the tutorial should start with a brief mention of ghc vs. ghci

Also, I think that the tutorials should have a bias / consistent structure of learning from a REPL / interactive session, and should be normalized with instructions at the top on how to get started in Mac, Linux and Windows.

adambard

added a commit
that referenced
this issue

Jun 30, 2013

@adambard

2 participants

@egonSchiele

@noahlz

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Haskell error function
  • Hashchain refused to start i2c error
  • Hdmi твч как исправить
  • Hdmi вход на телевизоре не работает как исправить
  • Hdims03 im03 ошибка e37

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии