31. Recursive factorial (simple)
Create recursive function f which returns the factorial of non-negative integer i, calculated from f(i-1)
创建递归函数f,该函数返回从f(i-1)计算的非负整数I的阶乘
func f(i int) int { if i == 0 { return 1 } return i * f(i-1) }
package main import ( "fmt" ) func f(i int) int { if i == 0 { return 1 } return i * f(i-1) } func main() { for i := 0; i <= 10; i++ { fmt.Printf("f(%d) = %d\n", i, f(i)) } }
输出
f(0) = 1 f(1) = 1 f(2) = 2 f(3) = 6 f(4) = 24 f(5) = 120 f(6) = 720 f(7) = 5040 f(8) = 40320 f(9) = 362880 f(10) = 3628800
fn f(n: u32) -> u32 { if n < 2 { 1 } else { n * f(n - 1) } } fn main() { println!("{}", f(4 as u32)); }
输出
24
or
fn factorial(num: u64) -> u64 { match num { 0 | 1=> 1, _ => factorial(num - 1) * num, } } fn main (){ println!("{}", factorial(0)); println!("{}", factorial(1)); println!("{}", factorial(2)); println!("{}", factorial(3)); println!("{}", factorial(4)); println!("{}", factorial(5)); }
输出
1 1 2 6 24 120
32. Integer exponentiation by squaring
Create function exp which calculates (fast) the value x power n. x and n are non-negative integers.
创建函数exp,计算(快速)x次方n的值。 x和n是非负整数
package main import "fmt" func exp(x, n int) int { switch { case n == 0: return 1 case n == 1: return x case n%2 == 0: return exp(x*x, n/2) default: return x * exp(x*x, (n-1)/2) } } func main() { fmt.Println(exp(3, 5)) }
输出
243
fn exp(x: u64, n: u64) -> u64 { match n { 0 => 1, 1 => x, i if i % 2 == 0 => exp(x * x, n / 2), _ => x * exp(x * x, (n - 1) / 2), } } fn main() { let x = 16; let n = 4; println!("{}", exp(x, n)); }
输出
65536
33. Atomically read and update variable
Assign variable x the new value f(x), making sure that no other thread may modify x between the read and the write.
为变量x分配新值f(x),确保在读和写之间没有其他线程可以修改x。
package main import ( "fmt" "sync" ) func main() { var lock sync.RWMutex x := 3 lock.Lock() x = f(x) lock.Unlock() fmt.Println(x) } func f(i int) int { return 2 * i }
6
use std::sync::Mutex; fn f(x: i32) -> i32 { x + 1 } fn main() { let x = Mutex::new(0); let mut x = x.lock().unwrap(); *x = f(*x); println!("{:?}", *x); }
输出
1
34. Create a set of objects
Declare and initialize a set x containing objects of type T.
声明并初始化一个包含t类型对象的集合x。
go
x := make(map[T]bool)
package main import "fmt" type T string func main() { // declare a Set (implemented as a map) x := make(map[T]bool) // add some elements x["A"] = true x["B"] = true x["B"] = true x["C"] = true x["D"] = true // remove an element delete(x, "C") for t, _ := range x { fmt.Printf("x contains element %v \n", t) }
x contains element D x contains element A x contains element B
or
x := make(map[T]struct{})
package main import "fmt" type T string func main() { // declare a Set (implemented as a map) x := make(map[T]struct{}) // add some elements x["A"] = struct{}{} x["B"] = struct{}{} x["B"] = struct{}{} x["C"] = struct{}{} x["D"] = struct{}{} // remove an element delete(x, "C") for t, _ := range x { fmt.Printf("x contains element %v \n", t) } }
x contains element B x contains element D x contains element A
use std::collections::HashSet; fn main() { let mut m = HashSet::new(); m.insert("a"); m.insert("b"); println!("{:?}", m); }
输出
{"a", "b"}
35. First-class function : compose
Implement a function compose (A -> C) with parameters f (A -> B) and g (B -> C), which returns composition function g ∘ f
用参数f (A -> B)和g (B -> C)实现一个函数compose (A -> C),返回composition函数g ∘ f
package main import "fmt" import "strconv" func compose(f func(A) B, g func(B) C) func(A) C { return func(x A) C { return g(f(x)) } } func main() { squareFromStr := compose(str2int, square) fmt.Println(squareFromStr("12")) } type A string type B int type C int func str2int(a A) B { b, _ := strconv.ParseInt(string(a), 10, 32) return B(b) } func square(b B) C { return C(b * b) }
144
fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a> where F: 'a + Fn(A) -> B, G: 'a + Fn(B) -> C { Box::new(move |x| g(f(x))) }
or
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C { move |x| g(f(x)) } fn main() { let f = |x: u32| (x * 2) as i32; let g = |x: i32| (x + 1) as f32; let c = compose(f, g); println!("{}", c(2)); }
输出
5
36. First-class function : generic composition
Implement a function compose which returns composition function g ∘ f for any functions f and g having exactly 1 parameter.
实现一个函数组合,该函数组合为任何恰好有1个参数的函数f和g返回组合函数g ∘ f。
package main import "fmt" func composeIntFuncs(f func(int) int, g func(int) int) func(int) int { return func(x int) int { return g(f(x)) } } func main() { double := func(x int) int { return 2 * x } addTwo := func(x int) int { return x + 2 } h := composeIntFuncs(double, addTwo) for i := 0; i < 10; i++ { fmt.Println(i, h(i), addTwo(double(i))) } }
0 2 2 1 4 4 2 6 6 3 8 8 4 10 10 5 12 12 6 14 14 7 16 16 8 18 18 9 20 20
fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a> where F: 'a + Fn(A) -> B, G: 'a + Fn(B) -> C { Box::new(move |x| g(f(x))) }
or
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C { move |x| g(f(x)) } fn main() { let f = |x: u32| (x * 2) as i32; let g = |x: i32| (x + 1) as f32; let c = compose(f, g); println!("{}", c(2)); }
输出
5
37. Currying
Transform a function that takes multiple arguments into a function for which some of the arguments are preset.
将一个接受多个参数的函数转换为一个预设了某些参数的函数。
package main import ( "fmt" "time" ) type Company string type Employee struct { FirstName string LastName string } func (e *Employee) String() string { return "<" + e.FirstName + " " + e.LastName + ">" } type Payroll struct { Company Company Boss *Employee Employee *Employee StartDate time.Time EndDate time.Time Amount int } // Creates a blank payroll for a specific employee with specific boss in specific company type PayFactory func(Company, *Employee, *Employee) Payroll // Creates a blank payroll for a specific employee type CustomPayFactory func(*Employee) Payroll func CurryPayFactory(pf PayFactory, company Company, boss *Employee) CustomPayFactory { return func(e *Employee) Payroll { return pf(company, boss, e) } } func NewPay(company Company, boss *Employee, employee *Employee) Payroll { return Payroll{ Company: company, Boss: boss, Employee: employee, } } func main() { me := Employee{"Jack", "Power"} // I happen to be head of the HR department of Richissim Inc. var myLittlePayFactory CustomPayFactory = CurryPayFactory(NewPay, "Richissim", &me) fmt.Println(myLittlePayFactory(&Employee{"Jean", "Dupont"})) fmt.Println(myLittlePayFactory(&Employee{"Antoine", "Pol"})) }
{Richissim <Jack Power> <Jean Dupont> 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0} {Richissim <Jack Power> <Antoine Pol> 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0}
fn add(a: u32, b: u32) -> u32 { a + b } fn main() { let add5 = move |x| add(5, x); let y = add5(12); println!("{}", y); }
输出
17
38. Extract a substring
Find substring t consisting in characters i (included) to j (excluded) of string s. Character indices start at 0 unless specified otherwise. Make sure that multibyte characters are properly handled.
查找由字符串s的字符I(包括)到j(不包括)组成的子字符串t。 除非另有说明,字符索引从0开始。 确保正确处理多字节字符。
package main import "fmt" func main() { s := "hello, utf-8 문자들" i, j := 7, 15 t := string([]rune(s)[i:j]) fmt.Println(t) }
utf-8 문자
extern crate unicode_segmentation; use unicode_segmentation::UnicodeSegmentation; fn main() { let s = "Lorem Ipsüm Dolor"; let (i, j) = (6, 11); let t = s.graphemes(true).skip(i).take(j - i).collect::<String>(); println!("{}", t); }
输出
Ipsüm
or
use substring::Substring; let t = s.substring(i, j);
39. Check if string contains a word
Set boolean ok to true if string word is contained in string s as a substring, or to false otherwise.
如果字符串单词作为子字符串包含在字符串s中,则将布尔ok设置为true,否则设置为false。
package main import ( "fmt" "strings" ) func main() { s := "Let's dance the macarena" word := "dance" ok := strings.Contains(s, word) fmt.Println(ok) word = "car" ok = strings.Contains(s, word) fmt.Println(ok) word = "duck" ok = strings.Contains(s, word) fmt.Println(ok) }
true true false
fn main() { let s = "Let's dance the macarena"; let word = "dance"; let ok = s.contains(word); println!("{}", ok); let word = "car"; let ok = s.contains(word); println!("{}", ok); let word = "duck"; let ok = s.contains(word); println!("{}", ok); }
输出
true true false