Problem Set 3: Haskell¶
The following questions are meant as practice for learning some basic features
of Haskell. Submit all your solutions in a single file named ps3.hs
.
Questions¶
Important: Include the most general type signature at the top of each function. Your code will be marked as wrong if the type signature is missing or incorrect!
(1 mark) Write a function called
is_bit x
that returnsTrue
whenx
is 0 or 1, andFalse
otherwise.Assume
x
is of typeInt
, and the type of the returned value isBool
.(1 mark) Write a function called
flip_bit x
that returns 1 ifx
is 0, and 0 ifx
is 1. Ifx
is not a bit, then callerror msg
, wheremsg
is a helpful error message string.Assume
x
is of typeInt
, and the type of the returned value is alsoInt
.In each of the following functions,
x
is a list ofInt
values, and the returned value has typeBool
.(1 mark) Write a function called
is_bit_seq1 x
that returnsTrue
ifx
is the empty list, or if it contains only bits (as determined byis_bit
).Use recursion and guarded commands in your solution.
(1 mark) Re-do the previous question, except this time name the function
is_bit_seq2 x
, and use recursion and at least one if-then-else expression in your solution. Don’t use any guarded commands.(1 mark) Re-do the previous question, except this time name the function
is_bit_seq3 x
, and use theall
function in your solution. Don’t use recursion, guarded commands, or if-then-else.
In each of the following functions,
x
a list ofInt
values, and the type the returned value is also a list ofInt
.(1 mark) Write a function called
invert_bits1 x
that returns a sequence of bits that is the same asx
, except 0s become 1s and 1s become 0s. For example,invert_bits1 [0,1,1,0]
returns[1,0,0,1]
.Use basic recursion in your solution.
(1 mark) Re-do the previous question, but name the function
invert_bits2 x
, and it implement it using themap
function (and no recursion).(1 mark) Re-do the previous question, but name the function
invert_bits3 x
, and it implement it using a list comprehension (and no recursion, and nomap
function).
(1 mark) Write a function called
bit_count x
that returns a pair of values indicating the number of 0s and 1s inx
. For example,bit_count [1,1,0,1]
returns the pair(1, 3)
.Assume
x
is a list ofInt
values, and only contains bits. The type of the returned value is(Int, Int)
.(1 mark) Write a function called
all_bit_seqs n
that returns a list of all bit sequences of length n. The order of the sequences doesn’t matter. Ifn
is less than 1, then return an empty list.Assume
n
is anInt
, and the returned value is a list ofInt
lists.