Search code examples
chaskellmonadscode-translationdo-notation

type tetris - stuck mixing monadic and pure code


I'm trying to implement bits and pieces of vulkan-tutorial in haskell.

For now im stuck trying to translate this code from c:

for (const char* layerName : validationLayers) {
    bool layerFound = false;

    for (const auto& layerProperties : availableLayers) {
        if (strcmp(layerName, layerProperties.layerName) == 0) {
            layerFound = true;
            break;
        }
    }

    if (!layerFound) {
        return false;
    }
}

return true; 

So far i got to this point:

-- This has type (Int -> Text) -> Bool
let partOne = all (`elem` requiredValidationLayers) . flip map [0 .. realCount-1]
-- This has type Int -> IO Text
let partTwo i = do
        let layerProperty = advancePtr layerProperties i
        myField_ <- readStringField @"layerName" layerProperty
        pure $ toS myField_ :: IO Text

I'm feeling that i have all the pieces here, but also that i might be going in a completely wrong direction.

How do i put this stuff together?

thanks

PS: ok, i just noticed that the set inclusion check is likely reversed - doesn't matter, lets for the sake of the question pretend that it's actually fine


Solution

  • thanks all commenters, i think i got it now :)

    this is how it looks like (inside a do block of IO () ):

    supportedLayers <- for [0 .. realCount-1] $ \i -> do
        let layerProperty = advancePtr layerProperties i
        myField_ <- readStringField @"layerName" layerProperty
        pure $ toS myField_ :: IO Text
    return $ requiredValidationLayers `includes` supportedLayers
    

    where

    includes :: Eq a => [a] -> [a] -> Bool
    includes a b = all (`elem` b) a