Haskell: lexical error in string/character literal at character 'i'

18.2k views Asked by At

I'm fairly new to Haskell programming and I'm having trouble understanding why I'm receiving this error in my code.

My problem is as follows: Any positive integer i can be expressed as i = 2^n*k, where k is odd, that is, as a power of 2 times an odd number. We call n the exponent of 2 in i. For example, the exponent of 2 in 40 is 3 (because 40 = 2^3*5) whereas the exponent of 2 in 42 is 1. If i itself is odd, then n is zero. If, on the other hand, i is even, that means it can be divided by 2. Write a function exponentOfTwo for finding the exponent of 2 in its argument.

I understand the psuedocode and it seems fairly simple: recursively divide i by 2 until result is odd, the number of times the division happens is n

here is my code (line 31-32):

exponentOfTwo :: Int -> Int  
exponentOfTwo i = if odd i then 0 else 1 + exponentOfTwo (i 'div' 2)  

I'm receiving the error "lexical error in string/character literal at character 'i'" on line 32 column 62.

I've tried searching for a solution to this error everywhere and so far I've had no luck.

2

There are 2 answers

0
AudioBubble On BEST ANSWER

To use a function in infix for, surround it with backticks (`), not with single quotes ('). The latter are for character literals, which, well are only one character long.

1
Jeremiah Willcock On

Are the characters around div backquotes rather than normal quotes? They need to be to allow a function name to be used as an infix operator. I changed that in your definition and the code worked for me.