1
votes

I am solving a problem in which I have to count all the even numbers in an array in purescript. I have written down code but I am facing type mismatch error.

import Data.Array (null)
import Data.Array.Partial (tail,head)
import Partial.Unsafe (unsafePartial)
import Math

iseven :: Int -> Boolean
iseven a = mod a 2 == 0


len :: forall a. Array a -> Int
len arr =
  if null arr
  then 0
  else
    if iseven unsafePartial head arr
      then 1 + len (unsafePartial tail arr)
      else len (unsafePartial tail arr)

But I am getting an error.

Error found:
in module $PSCI
at :6:18 - 6:40 (line 6, column 18 - line 6, column 40)

  Could not match type

    a1

  with type

    Int


while checking that type t0
  is at least as general as type Int
while checking that expression (unsafePartial head) arr
  has type Int
in binding group len

where a1 is a rigid type variable
        bound at (line 0, column 0 - line 0, column 0)
      t0 is an unknown type

I am new to purescript so I am not able to understand the error.

1
You have not posted your actual code. The error message could not have resulted from the code you posted. Please double check and amend.Fyodor Soikin
The line 6 is from len function means considering it at line 1K. Bakshi
No, you're definitely not. Specifically, the line iseven unsafePartial head arr is incorrect. Judging by the error you get, that line probably looks something like iseven (unsafePartial head arr). Please double check.Fyodor Soikin
Here is link to it ibb.co/rMQWgn8K. Bakshi
Your screenshot confirms exactly what I've been saying: your actual code is iseven (unsafePartial head arr), which is not what you posted in the question.Fyodor Soikin

1 Answers

2
votes

When you write unsafePartial head arr, that means "apply function unsafePartial to two arguments, first argument head and second argument arr, but this is not what you want to do.

What you want to do is first calculate head arr, and only then apply unsafePartial to the result of that.

To achieve this, use parentheses:

unsafePartial (head arr)

Or the $ operator:

unsafePartial $ head arr

After you have fixed that, the next error you're getting is about what iseven expects as argument and what you're passing to it. The signature of len says forall a. Array a ->, which means "I will work with arrays of any type", but in reality it's trying to pass an element of that array to iseven, which expects an Int. So your function promised to work with anything, but actually wants Int.

To fix, make the signature tell the truth: the function wants an array of Ints:

len :: Array Int -> Int