Skip to content
Brian Marick edited this page Sep 6, 2017 · 2 revisions

Full source

Exercise 1

valueInt : PropertyValue -> Maybe Int
valueInt value = 
  case value of
    Int int -> Just int
    _ -> Nothing

Exercise 2

isValueInt : PropertyValue -> Bool
isValueInt value = 
  valueInt value
    |> Maybe.map (always True)
    |> Maybe.withDefault False

Problem 3

unwrap : result -> (a -> result) -> Maybe a -> result
unwrap default transformer maybe =
  maybe
    |> Maybe.map transformer
    |> Maybe.withDefault default
       
isValueInt2 : PropertyValue -> Bool
isValueInt2 value = 
  valueInt value |> unwrap False (always True)

@gutierlf offers this variant unwrap:

unwrap : result -> (a -> result) -> Maybe a -> result
unwrap default f maybe =
    case maybe of
        Just x ->
            f x
        Nothing ->
            default

I think his is better, as it's more readable.

Problem 4

isJust : Maybe a -> Bool
isJust maybe = 
  maybe |> unwrap False (always True)
    
isValueInt3 : PropertyValue -> Bool
isValueInt3 value = 
  isJust (valueInt value)

Or, per @gutierlf, a version of isJust that's friendlier to the reader:

isJust : Maybe a -> Bool
isJust maybe =
    case maybe of
        Just _ -> True
        Nothing -> False

Many of the fancier Maybe functions are perhaps best used in pipelines, whereas plain case analysis works best without them.

Problem 5

isValueInt4 : PropertyValue -> Bool
isValueInt4 =
  valueInt >> isJust

Clone this wiki locally