WeixiangYan/CodeTransOcean huggingface dataset:
Task: Monads_Maybe monad


C++: #include <iostream>
#include <cmath>
#include <optional>
#include <vector>

using namespace std;


template <typename T>
auto operator>>(const optional<T>& monad, auto f)
{
    if(!monad.has_value())
    {
        
        
        return optional<remove_reference_t<decltype(*f(*monad))>>();
    }

    return f(*monad);
}


auto Pure(auto t)
{
    return optional{t};
}


auto SafeInverse(double v)
{
    if (v == 0)
    {
        return optional<decltype(v)>();
    }
    else
    {
        return optional(1/v);
    }
}


auto SafeAcos(double v)
{
    if(v < -1 || v > 1)
    {
        
        return optional<decltype(acos(v))>();
    }
    else
    {
        return optional(acos(v));
    }
}


template<typename T>
ostream& operator<<(ostream& s, optional<T> v)
{
    s << (v ? to_string(*v) : "nothing");
    return s;
}

int main()
{
    
    vector<double> tests {-2.5, -1, -0.5, 0, 0.5, 1, 2.5};
    
    cout << "x -> acos(1/x) , 1/(acos(x)\n";
    for(auto v : tests)
    {
        auto maybeMonad = Pure(v);
        auto inverseAcos = maybeMonad >> SafeInverse >> SafeAcos;
        auto acosInverse = maybeMonad >> SafeAcos >> SafeInverse;
        cout << v << " -> " << inverseAcos << ", " << acosInverse << "\n";
    }
}



Go: package main

import (
    "fmt"
    "strconv"
)

type maybe struct{ value *int }

func (m maybe) bind(f func(p *int) maybe) maybe {
    return f(m.value)
}

func unit(p *int) maybe {
    return maybe{p}
}

func decrement(p *int) maybe {
    if p == nil {
        return unit(nil)
    } else {
        q := *p - 1
        return unit(&q)
    }
}

func triple(p *int) maybe {
    if p == nil {
        return unit(nil)
    } else {
        q := (*p) * 3
        return unit(&q)
    }
}

func main() {
    i, j, k := 3, 4, 5
    for _, p := range []*int{&i, &j, nil, &k} {
        m1 := unit(p)
        m2 := m1.bind(decrement).bind(triple)
        var s1, s2 string = "none", "none"
        if m1.value != nil {
            s1 = strconv.Itoa(*m1.value)
        }
        if m2.value != nil {
            s2 = strconv.Itoa(*m2.value)
        }
        fmt.Printf("%4s -> %s\n", s1, s2)
    }
}
Task: Monads_Maybe monad



C#: using System;

namespace RosettaMaybe
{
    
    public abstract class Maybe<T>
    {
        public sealed class Some : Maybe<T>
        {
            public Some(T value) => Value = value;
            public T Value { get; }
        }
        public sealed class None : Maybe<T> { }
    }

    class Program
    {
        static Maybe<double> MonadicSquareRoot(double x)
        {
            if (x >= 0)
            {
                return new Maybe<double>.Some(Math.Sqrt(x));
            }
            else
            {
                return new Maybe<double>.None();
            }
        }
        static void Main(string[] args)
        {
            foreach (double x in new double[] { 4.0D, 8.0D, -15.0D, 16.23D, -42 })
            {
                Maybe<double> maybe = MonadicSquareRoot(x);
                if (maybe is Maybe<double>.Some some)
                {
                    Console.WriteLine($"The square root of {x} is " + some.Value);
                }
                else
                {
                    Console.WriteLine($"Square root of {x} is undefined.");
                }
            }
        }
    }
}


Go: package main

import (
    "fmt"
    "strconv"
)

type maybe struct{ value *int }

func (m maybe) bind(f func(p *int) maybe) maybe {
    return f(m.value)
}

func unit(p *int) maybe {
    return maybe{p}
}

func decrement(p *int) maybe {
    if p == nil {
        return unit(nil)
    } else {
        q := *p - 1
        return unit(&q)
    }
}

func triple(p *int) maybe {
    if p == nil {
        return unit(nil)
    } else {
        q := (*p) * 3
        return unit(&q)
    }
}

func main() {
    i, j, k := 3, 4, 5
    for _, p := range []*int{&i, &j, nil, &k} {
        m1 := unit(p)
        m2 := m1.bind(decrement).bind(triple)
        var s1, s2 string = "none", "none"
        if m1.value != nil {
            s1 = strconv.Itoa(*m1.value)
        }
        if m2.value != nil {
            s2 = strconv.Itoa(*m2.value)
        }
        fmt.Printf("%4s -> %s\n", s1, s2)
    }
}
Task: Monads_Maybe monad



C#: using System;

namespace RosettaMaybe
{
    
    public abstract class Maybe<T>
    {
        public sealed class Some : Maybe<T>
        {
            public Some(T value) => Value = value;
            public T Value { get; }
        }
        public sealed class None : Maybe<T> { }
    }

    class Program
    {
        static Maybe<double> MonadicSquareRoot(double x)
        {
            if (x >= 0)
            {
                return new Maybe<double>.Some(Math.Sqrt(x));
            }
            else
            {
                return new Maybe<double>.None();
            }
        }
        static void Main(string[] args)
        {
            foreach (double x in new double[] { 4.0D, 8.0D, -15.0D, 16.23D, -42 })
            {
                Maybe<double> maybe = MonadicSquareRoot(x);
                if (maybe is Maybe<double>.Some some)
                {
                    Console.WriteLine($"The square root of {x} is " + some.Value);
                }
                else
                {
                    Console.WriteLine($"Square root of {x} is undefined.");
                }
            }
        }
    }
}





Python: 
from __future__ import annotations

from typing import Any
from typing import Callable
from typing import Generic
from typing import Optional
from typing import TypeVar
from typing import Union


T = TypeVar("T")


class Maybe(Generic[T]):
    def __init__(self, value: Union[Optional[T], Maybe[T]] = None):
        if isinstance(value, Maybe):
            self.value: Optional[T] = value.value
        else:
            self.value = value

    def __rshift__(self, func: Callable[[Optional[T]], Maybe[Any]]):
        return self.bind(func)

    def bind(self, func: Callable[[Optional[T]], Maybe[Any]]) -> Maybe[Any]:
        return func(self.value)

    def __str__(self):
        return f"{self.__class__.__name__}({self.value!r})"


def plus_one(value: Optional[int]) -> Maybe[int]:
    if value is not None:
        return Maybe[int](value + 1)
    return Maybe[int](None)


def currency(value: Optional[int]) -> Maybe[str]:
    if value is not None:
        return Maybe[str](f"${value}.00")
    return Maybe[str](None)


if __name__ == "__main__":
    test_cases = [1, 99, None, 4]

    for case in test_cases:
        m_int = Maybe[int](case)
        result = m_int >> plus_one >> currency
        
        
        print(f"{str(case):<4} -> {result}")
Task: Monads_Maybe monad




Go: package main

import (
    "fmt"
    "strconv"
)

type maybe struct{ value *int }

func (m maybe) bind(f func(p *int) maybe) maybe {
    return f(m.value)
}

func unit(p *int) maybe {
    return maybe{p}
}

func decrement(p *int) maybe {
    if p == nil {
        return unit(nil)
    } else {
        q := *p - 1
        return unit(&q)
    }
}

func triple(p *int) maybe {
    if p == nil {
        return unit(nil)
    } else {
        q := (*p) * 3
        return unit(&q)
    }
}

func main() {
    i, j, k := 3, 4, 5
    for _, p := range []*int{&i, &j, nil, &k} {
        m1 := unit(p)
        m2 := m1.bind(decrement).bind(triple)
        var s1, s2 string = "none", "none"
        if m1.value != nil {
            s1 = strconv.Itoa(*m1.value)
        }
        if m2.value != nil {
            s2 = strconv.Itoa(*m2.value)
        }
        fmt.Printf("%4s -> %s\n", s1, s2)
    }
}




Python: 
from __future__ import annotations

from typing import Any
from typing import Callable
from typing import Generic
from typing import Optional
from typing import TypeVar
from typing import Union


T = TypeVar("T")


class Maybe(Generic[T]):
    def __init__(self, value: Union[Optional[T], Maybe[T]] = None):
        if isinstance(value, Maybe):
            self.value: Optional[T] = value.value
        else:
            self.value = value

    def __rshift__(self, func: Callable[[Optional[T]], Maybe[Any]]):
        return self.bind(func)

    def bind(self, func: Callable[[Optional[T]], Maybe[Any]]) -> Maybe[Any]:
        return func(self.value)

    def __str__(self):
        return f"{self.__class__.__name__}({self.value!r})"


def plus_one(value: Optional[int]) -> Maybe[int]:
    if value is not None:
        return Maybe[int](value + 1)
    return Maybe[int](None)


def currency(value: Optional[int]) -> Maybe[str]:
    if value is not None:
        return Maybe[str](f"${value}.00")
    return Maybe[str](None)


if __name__ == "__main__":
    test_cases = [1, 99, None, 4]

    for case in test_cases:
        m_int = Maybe[int](case)
        result = m_int >> plus_one >> currency
        
        
        print(f"{str(case):<4} -> {result}")
Task: Monads_Maybe monad

C: #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef enum type
{
  INT,
  STRING
} Type;

typedef struct maybe
{
  int i;
  char *s;
  Type t;
  _Bool is_something;
} Maybe;

void print_Maybe(Maybe *m)
{
  if (m->t == INT)
    printf("Just %d : INT\n", m->i);

  else if (m->t == STRING)
    printf("Just \"%s\" : STRING\n", m->s);

  else
    printf("Nothing\n");

}

Maybe *return_maybe(void *data, Type t)
{
  Maybe *m = malloc(sizeof(Maybe));
  if (t == INT)
  {
    m->i = *(int *) data;
    m->s = NULL;
    m->t = INT;
    m->is_something = true;
  }

  else if (t == STRING)
  {
    m->i = 0;
    m->s = data;
    m->t = STRING;
    m->is_something = true;
  }

  else
  {
    m->i = 0;
    m->s = NULL;
    m->t = 0;
    m->is_something = false;
  }

  return m;
}

Maybe *bind_maybe(Maybe *m, Maybe *(*f)(void *))
{
  Maybe *n = malloc(sizeof(Maybe));
  
  if (f(&(m->i))->is_something)
  {
    n->i = f(&(m->i))->i;
    n->s = f(&(m->i))->s;
    n->t = f(&(m->i))->t;
    n->is_something = true;
  }

  else
  {
    n->i = 0;
    n->s = NULL;
    n->t = 0;
    n->is_something = false;
  }
  return n;
}

Maybe *f_1(void *v) 
{
  Maybe *m = malloc(sizeof(Maybe));
  m->i = (*(int *) v) * (*(int *) v);
  m->s = NULL;
  m->t = INT;
  m->is_something = true;
  return m;
}

Maybe *f_2(void *v) 
{
  Maybe *m = malloc(sizeof(Maybe));
  m->i = 0;
  m->s = malloc(*(int *) v * sizeof(char) + 1);
  for (int i = 0; i < *(int *) v; i++)
  {
    m->s[i] = 'x';
  }
  m->s[*(int *) v + 1] = '\0';
  m->t = STRING;
  m->is_something = true;
  return m;
}

int main()
{
  int i = 7;
  char *s = "lorem ipsum dolor sit amet";

  Maybe *m_1 = return_maybe(&i, INT);
  Maybe *m_2 = return_maybe(s, STRING);

  print_Maybe(m_1); 
  print_Maybe(m_2); 

  print_Maybe(bind_maybe(m_1, f_1)); 
  print_Maybe(bind_maybe(m_1, f_2)); 

  print_Maybe(bind_maybe(bind_maybe(m_1, f_1), f_2)); 
}




Go: package main

import (
    "fmt"
    "strconv"
)

type maybe struct{ value *int }

func (m maybe) bind(f func(p *int) maybe) maybe {
    return f(m.value)
}

func unit(p *int) maybe {
    return maybe{p}
}

func decrement(p *int) maybe {
    if p == nil {
        return unit(nil)
    } else {
        q := *p - 1
        return unit(&q)
    }
}

func triple(p *int) maybe {
    if p == nil {
        return unit(nil)
    } else {
        q := (*p) * 3
        return unit(&q)
    }
}

func main() {
    i, j, k := 3, 4, 5
    for _, p := range []*int{&i, &j, nil, &k} {
        m1 := unit(p)
        m2 := m1.bind(decrement).bind(triple)
        var s1, s2 string = "none", "none"
        if m1.value != nil {
            s1 = strconv.Itoa(*m1.value)
        }
        if m2.value != nil {
            s2 = strconv.Itoa(*m2.value)
        }
        fmt.Printf("%4s -> %s\n", s1, s2)
    }
}
Task: Monads_Maybe monad


C++: #include <iostream>
#include <cmath>
#include <optional>
#include <vector>

using namespace std;


template <typename T>
auto operator>>(const optional<T>& monad, auto f)
{
    if(!monad.has_value())
    {
        
        
        return optional<remove_reference_t<decltype(*f(*monad))>>();
    }

    return f(*monad);
}


auto Pure(auto t)
{
    return optional{t};
}


auto SafeInverse(double v)
{
    if (v == 0)
    {
        return optional<decltype(v)>();
    }
    else
    {
        return optional(1/v);
    }
}


auto SafeAcos(double v)
{
    if(v < -1 || v > 1)
    {
        
        return optional<decltype(acos(v))>();
    }
    else
    {
        return optional(acos(v));
    }
}


template<typename T>
ostream& operator<<(ostream& s, optional<T> v)
{
    s << (v ? to_string(*v) : "nothing");
    return s;
}

int main()
{
    
    vector<double> tests {-2.5, -1, -0.5, 0, 0.5, 1, 2.5};
    
    cout << "x -> acos(1/x) , 1/(acos(x)\n";
    for(auto v : tests)
    {
        auto maybeMonad = Pure(v);
        auto inverseAcos = maybeMonad >> SafeInverse >> SafeAcos;
        auto acosInverse = maybeMonad >> SafeAcos >> SafeInverse;
        cout << v << " -> " << inverseAcos << ", " << acosInverse << "\n";
    }
}






Python: 
from __future__ import annotations

from typing import Any
from typing import Callable
from typing import Generic
from typing import Optional
from typing import TypeVar
from typing import Union


T = TypeVar("T")


class Maybe(Generic[T]):
    def __init__(self, value: Union[Optional[T], Maybe[T]] = None):
        if isinstance(value, Maybe):
            self.value: Optional[T] = value.value
        else:
            self.value = value

    def __rshift__(self, func: Callable[[Optional[T]], Maybe[Any]]):
        return self.bind(func)

    def bind(self, func: Callable[[Optional[T]], Maybe[Any]]) -> Maybe[Any]:
        return func(self.value)

    def __str__(self):
        return f"{self.__class__.__name__}({self.value!r})"


def plus_one(value: Optional[int]) -> Maybe[int]:
    if value is not None:
        return Maybe[int](value + 1)
    return Maybe[int](None)


def currency(value: Optional[int]) -> Maybe[str]:
    if value is not None:
        return Maybe[str](f"${value}.00")
    return Maybe[str](None)


if __name__ == "__main__":
    test_cases = [1, 99, None, 4]

    for case in test_cases:
        m_int = Maybe[int](case)
        result = m_int >> plus_one >> currency
        
        
        print(f"{str(case):<4} -> {result}")
Task: Monads_Maybe monad

C: #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef enum type
{
  INT,
  STRING
} Type;

typedef struct maybe
{
  int i;
  char *s;
  Type t;
  _Bool is_something;
} Maybe;

void print_Maybe(Maybe *m)
{
  if (m->t == INT)
    printf("Just %d : INT\n", m->i);

  else if (m->t == STRING)
    printf("Just \"%s\" : STRING\n", m->s);

  else
    printf("Nothing\n");

}

Maybe *return_maybe(void *data, Type t)
{
  Maybe *m = malloc(sizeof(Maybe));
  if (t == INT)
  {
    m->i = *(int *) data;
    m->s = NULL;
    m->t = INT;
    m->is_something = true;
  }

  else if (t == STRING)
  {
    m->i = 0;
    m->s = data;
    m->t = STRING;
    m->is_something = true;
  }

  else
  {
    m->i = 0;
    m->s = NULL;
    m->t = 0;
    m->is_something = false;
  }

  return m;
}

Maybe *bind_maybe(Maybe *m, Maybe *(*f)(void *))
{
  Maybe *n = malloc(sizeof(Maybe));
  
  if (f(&(m->i))->is_something)
  {
    n->i = f(&(m->i))->i;
    n->s = f(&(m->i))->s;
    n->t = f(&(m->i))->t;
    n->is_something = true;
  }

  else
  {
    n->i = 0;
    n->s = NULL;
    n->t = 0;
    n->is_something = false;
  }
  return n;
}

Maybe *f_1(void *v) 
{
  Maybe *m = malloc(sizeof(Maybe));
  m->i = (*(int *) v) * (*(int *) v);
  m->s = NULL;
  m->t = INT;
  m->is_something = true;
  return m;
}

Maybe *f_2(void *v) 
{
  Maybe *m = malloc(sizeof(Maybe));
  m->i = 0;
  m->s = malloc(*(int *) v * sizeof(char) + 1);
  for (int i = 0; i < *(int *) v; i++)
  {
    m->s[i] = 'x';
  }
  m->s[*(int *) v + 1] = '\0';
  m->t = STRING;
  m->is_something = true;
  return m;
}

int main()
{
  int i = 7;
  char *s = "lorem ipsum dolor sit amet";

  Maybe *m_1 = return_maybe(&i, INT);
  Maybe *m_2 = return_maybe(s, STRING);

  print_Maybe(m_1); 
  print_Maybe(m_2); 

  print_Maybe(bind_maybe(m_1, f_1)); 
  print_Maybe(bind_maybe(m_1, f_2)); 

  print_Maybe(bind_maybe(bind_maybe(m_1, f_1), f_2)); 
}


C++: #include <iostream>
#include <cmath>
#include <optional>
#include <vector>

using namespace std;


template <typename T>
auto operator>>(const optional<T>& monad, auto f)
{
    if(!monad.has_value())
    {
        
        
        return optional<remove_reference_t<decltype(*f(*monad))>>();
    }

    return f(*monad);
}


auto Pure(auto t)
{
    return optional{t};
}


auto SafeInverse(double v)
{
    if (v == 0)
    {
        return optional<decltype(v)>();
    }
    else
    {
        return optional(1/v);
    }
}


auto SafeAcos(double v)
{
    if(v < -1 || v > 1)
    {
        
        return optional<decltype(acos(v))>();
    }
    else
    {
        return optional(acos(v));
    }
}


template<typename T>
ostream& operator<<(ostream& s, optional<T> v)
{
    s << (v ? to_string(*v) : "nothing");
    return s;
}

int main()
{
    
    vector<double> tests {-2.5, -1, -0.5, 0, 0.5, 1, 2.5};
    
    cout << "x -> acos(1/x) , 1/(acos(x)\n";
    for(auto v : tests)
    {
        auto maybeMonad = Pure(v);
        auto inverseAcos = maybeMonad >> SafeInverse >> SafeAcos;
        auto acosInverse = maybeMonad >> SafeAcos >> SafeInverse;
        cout << v << " -> " << inverseAcos << ", " << acosInverse << "\n";
    }
}
Task: QR decomposition



C#: using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;


class Program
{

    static void Main(string[] args)
    {
        Matrix<double> A = DenseMatrix.OfArray(new double[,]
        {
                {  12,  -51,    4 },
                {   6,  167,  -68 },
                {  -4,   24,  -41 }
        });
        Console.WriteLine("A:");
        Console.WriteLine(A);
        var qr = A.QR();
        Console.WriteLine();
        Console.WriteLine("Q:");
        Console.WriteLine(qr.Q);
        Console.WriteLine();
        Console.WriteLine("R:");
        Console.WriteLine(qr.R);
    }
}


Go: package main

import (
    "fmt"
    "math"

    "github.com/skelterjohn/go.matrix"
)

func sign(s float64) float64 {
    if s > 0 {
        return 1
    } else if s < 0 {
        return -1
    }
    return 0
}

func unitVector(n int) *matrix.DenseMatrix {
    vec := matrix.Zeros(n, 1)
    vec.Set(0, 0, 1)
    return vec
}

func householder(a *matrix.DenseMatrix) *matrix.DenseMatrix {
    m := a.Rows()
    s := sign(a.Get(0, 0))
    e := unitVector(m)
    u := matrix.Sum(a, matrix.Scaled(e, a.TwoNorm()*s))
    v := matrix.Scaled(u, 1/u.Get(0, 0))
    
    prod, _ := v.Transpose().TimesDense(v)
    β := 2 / prod.Get(0, 0)

    prod, _ = v.TimesDense(v.Transpose())
    return matrix.Difference(matrix.Eye(m), matrix.Scaled(prod, β))
}

func qr(a *matrix.DenseMatrix) (q, r *matrix.DenseMatrix) {
    m := a.Rows()
    n := a.Cols()
    q = matrix.Eye(m)

    last := n - 1
    if m == n {
        last--
    }
    for i := 0; i <= last; i++ {
        
        b := a.GetMatrix(i, i, m-i, n-i).Copy()
        x := b.GetColVector(0)
        h := matrix.Eye(m)
        h.SetMatrix(i, i, householder(x))
        q, _ = q.TimesDense(h)
        a, _ = h.TimesDense(a)
    }
    return q, a
}

func main() {
    
    a := matrix.MakeDenseMatrixStacked([][]float64{
        {12, -51, 4},
        {6, 167, -68},
        {-4, 24, -41}})
    q, r := qr(a)
    fmt.Println("q:\n", q)
    fmt.Println("r:\n", r)

    
    x := matrix.MakeDenseMatrixStacked([][]float64{
        {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}})
    y := matrix.MakeDenseMatrixStacked([][]float64{
        {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}})
    fmt.Println("\npolyfit:\n", polyfit(x, y, 2))
}

func polyfit(x, y *matrix.DenseMatrix, n int) *matrix.DenseMatrix {
    m := x.Cols()
    a := matrix.Zeros(m, n+1)
    for i := 0; i < m; i++ {
        for j := 0; j <= n; j++ {
            a.Set(i, j, math.Pow(x.Get(0, i), float64(j)))
        }
    }
    return lsqr(a, y.Transpose())
}

func lsqr(a, b *matrix.DenseMatrix) *matrix.DenseMatrix {
    q, r := qr(a)
    n := r.Cols()
    prod, _ := q.Transpose().TimesDense(b)
    return solveUT(r.GetMatrix(0, 0, n, n), prod.GetMatrix(0, 0, n, 1))
}

func solveUT(r, b *matrix.DenseMatrix) *matrix.DenseMatrix {
    n := r.Cols()
    x := matrix.Zeros(n, 1)
    for k := n - 1; k >= 0; k-- {
        sum := 0.
        for j := k + 1; j < n; j++ {
            sum += r.Get(k, j) * x.Get(j, 0)
        }
        x.Set(k, 0, (b.Get(k, 0)-sum)/r.Get(k, k))
    }
    return x
}
Task: QR decomposition



C#: using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;


class Program
{

    static void Main(string[] args)
    {
        Matrix<double> A = DenseMatrix.OfArray(new double[,]
        {
                {  12,  -51,    4 },
                {   6,  167,  -68 },
                {  -4,   24,  -41 }
        });
        Console.WriteLine("A:");
        Console.WriteLine(A);
        var qr = A.QR();
        Console.WriteLine();
        Console.WriteLine("Q:");
        Console.WriteLine(qr.Q);
        Console.WriteLine();
        Console.WriteLine("R:");
        Console.WriteLine(qr.R);
    }
}





Python: 

import numpy as np

def qr(A):
    m, n = A.shape
    Q = np.eye(m)
    for i in range(n - (m == n)):
        H = np.eye(m)
        H[i:, i:] = make_householder(A[i:, i])
        Q = np.dot(Q, H)
        A = np.dot(H, A)
    return Q, A

def make_householder(a):
    v = a / (a[0] + np.copysign(np.linalg.norm(a), a[0]))
    v[0] = 1
    H = np.eye(a.shape[0])
    H -= (2 / np.dot(v, v)) * np.dot(v[:, None], v[None, :])
    return H


a = np.array(((
    (12, -51,   4),
    ( 6, 167, -68),
    (-4,  24, -41),
)))

q, r = qr(a)
print('q:\n', q.round(6))
print('r:\n', r.round(6))


def polyfit(x, y, n):
    return lsqr(x[:, None]**np.arange(n + 1), y.T)

def lsqr(a, b):
    q, r = qr(a)
    _, n = r.shape
    return np.linalg.solve(r[:n, :], np.dot(q.T, b)[:n])

x = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
y = np.array((1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321))

print('\npolyfit:\n', polyfit(x, y, 2))