data Bool = { True, False }

data List a = { Nil, Cons a (List a) }

defn if c t e = {
    case c of {
        True -> { t }
        False -> { e }
    }
}

defn mergeUntil l r p = {
    let {
        defn mergeLeft nl nr = {
            case nl of {
                Nil -> { Nil }
                Cons x xs -> { if (p x) (Cons x (mergeRight xs nr)) Nil }
            }
        }
        defn mergeRight nl nr = {
            case nr of {
                Nil -> { Nil }
                Cons x xs -> { if (p x) (Cons x (mergeLeft nl xs)) Nil }
            }
        }
    } in {
        mergeLeft l r
    }
}

defn const x y = { x }

defn sum l = {
    case l of {
        Nil -> { 0 }
        Cons x xs -> { x + sum xs }
    }
}

defn main = {
    let {
        defn firstList = { Cons 1 (Cons 3 (Cons 5 Nil)) }
        defn secondList = { Cons 2 (Cons 4 (Cons 6 Nil)) }
    } in {
        sum (mergeUntil firstList secondList (const True))
    }
}
