53.8k views
0 votes
Write a Haskell function even Length :: [a]→ Bool and the corresponding Prolog predicate even Length, which returns (or resolves to) true when the single list argument passed to it has even length. Note: that these must be written from scratch, so no previously defined functions may be used, e.g., the Prelude length function (or the Prolog length predicate) may not be used - your solutions will be recursive. You may, of course define auxiliary helper functions (which also must be written from scratch), e.g. the appropriate Odd Length :: [a] → Bool might be useful in Haskell, and similarly, an Odd Length predicate in Prolog. The idea is that in Haskell, e.g., Even Length [1,2,3,4] would return True, and Wavelength "hey" would return False, while in Prolog, e.g., the query Even length ([1,2,3,4]). would resolve to true, and the query Even length ([a,b,c]). would resolve to false

User Vesuvious
by
7.5k points

1 Answer

4 votes

Final answer:

To write a Haskell function evenLength and a Prolog predicate even_length that return true if the list has an even length, we can use recursive approaches.

Step-by-step explanation:

To write a Haskell function evenLength, we can use a recursive approach:

evenLength :: [a] -> Bool
evenLength [] = True
evenLength [_] = False
evenLength (_:_:xs) = evenLength xs

This function checks if the list is empty or contains only one element, in which case it returns true or false respectively. Otherwise, it recursively calls itself with the tail of the list.

In Prolog, the corresponding predicate even_length can be defined as:

even_length([]).
even_length([_, _ | T]) :- even_length(T).

This Prolog predicate checks if the list is empty or contains only one element, in which case it succeeds. Otherwise, it uses pattern matching to discard the first two elements and recursively calls itself with the remaining tail of the list.

User Kysha
by
7.5k points