Working with lists
For list operations, only the
Head
,Prepend
andTail
functions, as well as the functions implemented in previous problems, are allowed, and no other functions are permitted.
Find the number of elements of a list.
Example:
Eq[MyLength[{#a, #b, #c, #d}], 4];
Solution
Let[MyLength, Fun[{list},
Block[
Let[MyLength', Fun[{sub, n},
If[Eq[Length[sub], 0], n,
MyLength'[Tail[sub], Add[n, 1]]]]],
MyLength'[list, 0]]]];
Find the last box of a list.
Example:
Eq[MyLast[{#a, #b, #c, #d}], #d];
Solution
Let[MyLast, Fun[{list},
If[Eq[MyLength[list], 0], {#err, "empty list"},
If[Eq[MyLength[list], 1], Head[list], MyLast[Tail[list]]]]]];
Find the last but one box of a list.
Example:
Eq[MyButLast[{#a, #b, #c, #d}], {#c, #d}];
Solution
Let[MyButLast, Fun[{list},
If[Less[MyLength[list], 2], {#err, "short list"},
If[Eq[MyLength[list], 2], list, MyButLast[Tail[list]]]]]];
Find the K’th element of a list.
The first element in the list is number 1.
Example:
Eq[MyIndex[{#a, #b, #c, #d}, 3], #c];
Solution
Let[MyIndex, Fun[{list, n},
If[Less[n, 1], {#err, "invalid index"},
If[Eq[n, 1], Head[list], MyIndex[Tail[list], Sub[n, 1]]]]]];
Reverse a list.
Example:
Eq[MyReverse[{#a, #b, #c, #d, #e}], {#e, #d, #c, #b, #a}];
Solution
Let[MyReverse, Fun[{list},
Block[
Let[MyReverse', Fun[{sub, acc},
If[Eq[Length[sub], 0], acc,
MyReverse'[Tail[sub], Prepend[acc, Head[sub]]]]]],
MyReverse'[list, {}]]]];
Find out whether a list is a palindrome.
Example:
IsPalindrome[{#a, #c, #b, #c, #a}];
Solution
Let[IsPalindrome, Fun[{list}, Eq[MyReverse[list], list]]];
Flatten a nested list structure.
Example:
Eq[MyFlatten[{#a, {#b, {#c, #d}, #e}}], {#a, #b, #c, #d, #e}];
Solution
Let[MyListConcat, Fun[{list1, list2},
Block[
Let[MyListConcat', Fun[{list1, list2},
If[Eq[MyLength[list2], 0], list1,
MyListConcat'[Prepend[list1, Head[list2]], Tail[list2]]]]],
MyReverse[MyListConcat'[MyReverse[list1], list2]]]]];
Let[MyFlatten, Fun[{list},
Block[
Let[MyFlatten', Fun[{sub, acc},
If[Eq[Length[sub], 0], acc,
MyFlatten'[Tail[sub],
If[IsList[Head[sub]],
MyListConcat[MyFlatten'[Head[sub], {}], acc],
Prepend[acc, Head[sub]]]]]]],
MyReverse[MyFlatten'[list, {}]]]]];
Eliminate consecutive duplicates of list elements.
Example:
Eq[Compress[{#a, #a, #a, #a, #b, #c, #c, #a, #a, #d, #e, #e, #e, #e}],
{#a, #b, #c, #a, #d, #e}];
Solution
Let[Compress, Fun[{list},
Block[
Let[Compress', Fun[{list, acc},
If[Eq[Length[list], 0], acc,
Compress'[Tail[list],
If[Eq[Head[list], Head[acc]],
acc, Prepend[acc, Head[list]]]]]]],
MyReverse[Compress'[Tail[list], { Head[list] }]]]]];