Haskell compare two int with if statement

时间:2019-04-08 13:43:21

标签: if-statement haskell

I want to implement a function named log2, which computes the integer log (base 2) of its argument. I can't use log function. My solution is: to check if x equals to 2^y. If x equals 2^y give the value y, if x doesn't equals to 2^y then y = y + 1. This will go on until y is found. This is what I got so far:

log2 x = y where y = 0
    if x == 2^y then y
    else y = y + 1

When I want to run this I will get this error:

error: parse error on input `if'

I am new to Haskell so can somebody explain me what's wrong?

1 个答案:

答案 0 :(得分:3)

It is difficult to explain precisely why the syntax error arises, given that it is not obvious to what (valid) syntax it is intended to correspond. Suffice to say you have essentially written log2 x = 0 if ...... One might expect the second phrase to be a definition or part of the same expression as the 0, but if begins neither.

More generally, Haskell does not have mutable variables. You cannot "assign" to y. The closest to what you want would be something like,

log2 x = until (\y -> x == 2^y) (\y -> y + 1) 0

Notice that we are never assigning to y, we simply bind it to execute each lambda expression. We can imagine it receiving a different name each time! and that would be fine.