A list of integers can be recursively defined as follows:
<IntList> ::= [] | cons(<Int>, <IntList>)Write a recursive function named
allEqualTothat takes an integer and a list as input, and returns1if all the numbers in the list are equal to the given integer, and0otherwise. For example,allEqualTo(5, cons(5, cons(5, [])))should return1, andallEqualTo(5, cons(5, cons(3, cons(5, []))))should return0.NOTE: Write a function, not a Prolog predicate or code in any other language. Feel free to use pattern matching.
This is what I did and when I checked answers, they did it in a totally different way, but I am still not convinced this is wrong, so I’m asking here.
allEqualTo(x, []) = 0
allEqualTo(x, cons(x, [])) = 1
allEqualTo(x, cons(y, a)) = 0
allEqualTo(x, cons(x, a)) = cons(x, allEqualTo(x, cons(x, a))
Edit: The solution looks like:
allEqualTo(x, []) = 0
allEqualTo(x, cons(x, [])) = 1
allEqualTo(x, cons(y, a)) = 0 x≠y
allEqualTo(x, cons(x, a)) = allEqualTo(x, L)
allEqualToreturns an integer.allEqualTo(x,[])should equal 1: indeed every element in the list is equal tox.conswith infix notationcons(x,xs) ≡ x :: xs.Consider functions
and : Int → Int → Intand infix(==) : Int → Int → Intthat behave like their corresponding bool-valued versions but with0instead ofFalseand1instead ofTrue.Given an integer
xand a lista :: b :: c :: []you want to return1ifa=b=c=xand0otherwise.Notice that if you map the
[]to1and the(::)to the functionλy,b. x == y and b, you would map the last list to the intwhich is what we want. If you have a
foldimplemented you can write up to curryingwhere
fold : ∀a,b. b → (a → b → b) → [a] → b.If you want a construction with pattern matching you can unfold this definition (up to currying) to get
Notice here it's key that
allEqualTo(x, []) = 1since otherwise when you get to the end of the list you'll always return0.Also this maps the unit of the list to the ("multiplicative" --
and) unit of the booleans, and since it's theandwhat you are using for the recursive case, this makes yourallEqualToan algebra morphism. Doing otherwise would be unnatural.Here's a nice introduction to the topic of $F$-algebras. Although it might require some extra reading beforehand.
Ask anything, hope this helps!