Search code examples
elm

Create condition on type variants in a list


So I have some type variants in a list:

type VariableType
    = BooleanVariable
    | ContinuousVariable
    | CategoricalVariable
    | Incorrect

mylistone = [ContinuousVariable, ContinuousVariable, ContinuousVariable]
mylisttwo = [ContinuousVariable, ContinuousVariable, CategoricalVariable]

I need to have a function defined as such:

listtype : List VariableType -> VariableType
listtype list =
    -- if (List.all isBooleanVariable list) then 
        BooleanVariable
    -- else if (List.all isContinuousVariable list) then 
        ContinuousVariable
    -- else
        CategoricalVariable

So the output on these two lists defined above should be:

listtype mylistone -- ContinuousVariable
listtype mylisttwo -- CategoricalVariable

But I read that it was impossible to check types after compilation type, because of type erasure. How can I define isBooleanVariable and isContinuousVariable?


Solution

  • BooleanVariable, ContinuousVariable etc. are all variants of the custom type VariableType and produces or represents values. So you're not actually trying to check the type of these, they all have the type VariableType, just their value. Which can be done with the equality operator, as with any other comparable value:

    listtype : List VariableType -> VariableType
    listtype list =
        if (List.all (\v -> v == BooleanVariable) list) then 
            BooleanVariable
        else if (List.all ((==) ContinuousVariable) list) then 
            ContinuousVariable
        else
            CategoricalVariable