This is an old revision of the document!
Function composition and function application
29. Sometimes it really helps to define function via function composition. For instance:
f x = (g.h) x where g x = 2*x h x = x + 1
What type does f have? What type does g have?
What does the following function do?
f x = ff x where g x = 2*x h x = x + 1 ff = f.h
What does the following function do?
f x = ff x where g x = 2*x h x = x + 1 ff = h.f
30. Rewrite exercise 28 via function composition:
f l =
34. Sometimes it helps to use functions in infix form. For instance, instead of mod x 2
, we can write x mod 2
. We can also define infix functions:
x 'f' y = x + y
Implement a function for transforming lists into pairs, in exercise 32. and use it in the infix form.
35. Just in the same way, we can treat infix functions as prefix. We do this using round parentheses. Test:
:t (+) :t (&&) :t (++)
36. What about function composition? Is it a special operator, or is it just a function as well? What does :t (.)
do?
37. What does the function below do? Take parts of the function below, and test them.
f l = (((++) "?").((:) '>')) l
How about?
f = (((:) '>').(++"?"))
38. Write a function of a single line, such that:
f "Matei" = "{Matei}"
39. Use only (:)
, reverse
and functional composition .
to solve exercise 38
40. What does the function ($)
to?
(Use :t, and make up some tests)
41. Write the following implementation using only ($):
f "||" "Matei" = "||Matei||"
42. Solve exercise 13. from Lab 2 using $
(++
and reverse
are also permitted) and other improvements (treat the case when the list has fewer elements):