[Haskell-beginners] Improve my FFI code please...

David Virebayre dav.vire+haskell at gmail.com
Fri Jan 21 10:38:30 CET 2011


2011/1/21  <sean at objitsu.com>:
> Edward, Daniel, thanks.
>
>> On Friday 21 January 2011 00:35:02, Sean Charles wrote:
>> wiiOpen :: String -> IO (Maybe (Ptr Word8))
>> wiiOpen wid = do
>> ? ?handle <- withCString wid c_wiimote_open
>> ? ?case handle of
>> ? ? ?nullPtr -> return Nothing
>> ? ? ?handle -> return (Just handle)
>> Unless nullPtr is a macro that gets replaced with a literal by the
>> preprocessor, that won't do what you want. "nullPtr" is a generic name and
>> matches everything, so you'll always take the first branch (with -Wall,
>> ghc
>> should warn about overlapping patterns in that case).
>
> Daniel, you have confused me. In my RWH book there is a test from the PCRE
> example of nullPtr == x, so I just did my code using a case instead, I am
> sure it's correct!?!?!?   If I run my program with the Wiimote off, it

It's not correct, pattern matching and equality testing is not the same thing.

case handle of
    nullPtr -> return Nothing
    handle -> return (Just handle)

here nullPtr and handle are new variables you introduce for pattern matching.
naming one of them nullPtr is confusing because it's not trying to
compare handle to nullPtr.
it's basically saying:
1) if I can define nullPtr = handle, then return nothing
2) if I can define handle = handle, then return (Just handle)

You see that in 1) you can always define nullPtr = handle, so the
first case will always succeed.
also in 2) it's a bit silly to pattern match a variable with a
variable having the same name.

if handle == nullPtr then return Nothing else return (Just handle)

this is not the same thing, because here you test handle against
nullPtr for equality, which implies nullPtr is already defined.

David.



More information about the Beginners mailing list