scp = 
        Function[{f, g}, 
          Integrate[f[x]*g[x], {x, 0, 1}]];
v[n_] = Function[x, Cos[2*Pi*n*x]];
w[n_] = Function[x, Sin[2*Pi*n*x]];

l2norm  =  Function[f, Sqrt[scp[f, f]]]

funcminus[f_, g_] = 
        Function[x, f[x] - g[x]];
l2dist[f_, g_] = l2norm[funcminus[f, g]]

vt[n_] = 
        Function[x, v[n][x]/l2norm[v[n]]];
wt[n_] = Function[x, w[n][x]/l2norm[w[n]]];

proj[n_, f_] = 
      Function[x, 
        scp[f, vt[0]]*vt[0][x] + 
          Sum[scp[f, vt[k]]*vt[k][x] + scp[f, wt[k]]*wt[k][x], {k, 1, 
              n}]]

f = Function[x, 1 - x^2];

Plot[f[x], {x, 0, 1}]

f3 = proj[3, f]

Plot[f3[x], {x, 0, 1}]

N[l2dist[f3, f]]

f5 = proj[5, f]

Plot[f5[x], {x, 0, 1}]

N[l2dist[f5, f]]

g = 
        Function[x, 
          If[x < 0.5, Sin[2*Pi*x]*Cos[2*Pi*x], 
            0.5*Sin[2*Pi*x]*Cos[2*Pi*x]]];

Plot[g[x], {x, 0, 1}]

g3 = proj[3, g];

Plot[g3[x], {x, 0, 1}]

N[l2dist[g3, g]]

g5 = proj[5, g];

Plot[g5[x], {x, 0, 1}]

N[l2dist[g5, g]]

h = Function[x, If[x < 0.5, 2*x, 1 - 2*(x - 0.5)]];

Plot[h[x], {x, 0, 1}]

h3 = proj[3, h];

Plot[h3[x], {x, 0, 1}]

N[l2dist[h3, h]]

h5 = proj[5, h];

Plot[h5[x], {x, 0, 1}]

N[l2dist[h5, h]]

s = Function[x, x*Sin[8*Pi*x]];

Plot[s[x], {x, 0, 1}]

s3 = proj[3, s];

Plot[s3[x], {x, 0, 1}]

N[l2dist[s3, s]]

s5 = proj[5, s];

Plot[s5[x], {x, 0, 1}]

N[l2dist[s5, s]]

r = 
        Function[x, 
          If[x < 0.1, 10*x, 
            If[x < 0.4, 1, 
              If[x < 0.6, -10*(x - 0.5), 
                If[x < 0.9, -1, 10 (x - 1)]]]]];

Plot[r[x], {x, 0, 1}]

r3 = proj[3, r];

Plot[r3[x], {x, 0, 1}]

l2dist[r3, r]

r5 = proj[5, r];

Plot[r5[x], {x, 0, 1}]