0

I am new to haskell and stuck with the input parse error on '=' I was trying a function to check if a number is prime Here is the function -

isprime x
| x<=1 = "not prime"
| x == 2 = "yes"
| a = floor (sqrt x)
  lis = [2..a]
  divbylis (headlis:taillis)
    | length taillis <=0 = "yes it is prime"
    | x 'mod' headlis == 0 = "No not prime"
    | otherwise = divbylis taillis**

and it shows the error -

first.hs:58:15: error:
parse error on input ‘=’
Perhaps you need a 'let' in a 'do' block?
e.g. 'let x = 5' instead of 'x = 5'

line 58 is the line with declaration of lis = [2..a]**

jatin
  • 17
  • 1
  • 2
    You write `a = floor (sqrt 5)`, which makes no sense since Haskell expects a guard. – Willem Van Onsem Jul 13 '18 at 09:26
  • Did you maybe mean to have a `where` block somewhere? – AJF Jul 13 '18 at 09:28
  • 1
    The `| a = floor (sqrt x)` line is weird - what's a? I think you meant to write a `where` at the end of that line, but that won't fix the problem you're having here. – Cubic Jul 13 '18 at 09:29
  • Just using the common code of checking prime , creating a list of numbers from 2 to sqrt of the number and dividing by each of them – jatin Jul 13 '18 at 11:47
  • @jatin: but what you do is using *imperative style* code into a functional/declarative language. One of the ideas behind Haskell is to move away from that imperative approach. – Willem Van Onsem Jul 13 '18 at 11:52

1 Answers1

2

Here is some feedback:

  • You posted some code and a syntax error, but you didn't ask a question. Presumably your question is "Why doesn't this code work?" but that's actually not a good question. How do I ask a good question?

  • Your function is a predicate, but it returns a String. Consider returning a Bool instead.

  • Give your function a type signature:

    isprime :: Int -> Bool
    isprime ...
    
  • Your main syntax error is due to indentation; your guards are at the top-level. Write at least one space before the guards:

    isprime :: Int -> Bool
    isprime x
      | x <= 1 = False
      | x == 2 = True
      | ...
    
  • Use pattern matching when appropriate:

    isprime :: Int -> Bool
    isprime 1 = False
    isprime 2 = True
    isprime n = ...
    
  • I'm not reaaally sure what goes on at the "lis = [2..a]" and "divbylis (headlis:taillis)" part. It doesn't look like Haskell code. Is that supposed to be a helper function?

  • If writing a prime function is too difficult, then try writing simpler numeric, recursive functions like factorial, power, fibonacci, collatz. If you want to see how others have done it, see: Determining if a given number is a prime in haskell, Is there a better way to write the isPrime function?

sshine
  • 15,635
  • 1
  • 41
  • 66
  • Thanks, headlis is just the first element of the list and taillis is the remaining list. My bad , it was my first question on stackoverflow and also thanks for your concerns – jatin Jul 13 '18 at 11:49