1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338

//! This library allows you to do three things. It allows you to Create a function that
//! returns a constant f(x) -> 4, create a function that returns its input f(x) -> x, and
//! then do arithmatic with them and store the result f(x) -> x, g(x) -> 4, h = f*g => h ~= 4*x
//! then you can do whatever you want with the resulting Arc<Fn(T) -> T> where T is essentially
//! an f64 or other similar type

// #![feature(const_trait_impl)]

use std::ops::{
	Add,
	Sub,
	Mul,
	Div
};

use std::sync::Arc;

fn make_domain(start: i32, end: i32, step: f32) -> Vec<f64> {
	let start = (start as f32/step) as i64;
	let end = (end as f32/step) as i64;
	(start..=end).map(|x| {
		(x as f64)*step as f64
	}).collect()
}

pub trait Rational: Clone + Copy + Add<Output=Self> + Sub<Output=Self> + Mul<Output=Self> + Div<Output=Self>
 + From<f64> + PartialEq + std::fmt::Debug + std::cmp::PartialOrd {
	fn pow(self, rhs: Self) -> Self;
}

impl Rational for f64 {
	fn pow(self, rhs: Self) -> Self {
		self.powf(rhs)
	}
}

/// the main Function type of the library
#[derive(Clone)]
pub struct Function<T = f64> where T: Rational, {
	function: Arc<dyn Fn(T) -> T>
}

unsafe impl<T: Rational> Send for Function<T> {}

impl<T: Rational + 'static> Function<T> {
	/// return a contant function that returns the value of value
	pub fn new(value: f64) -> Self {
		Self {
			function: Arc::new(move |_x| value.into())
		}
	}
	
	pub fn new_t(value: T) -> Self {
		Self { function: Arc::new(move |_x| value)}
	}
	
	/// raise a function to the power of another
	pub fn pow(self, rhs: Self) -> Self {
		Self { function: Arc::new(move |x| (self.function)(x).pow((rhs.function)(x))) }
	}
	
	pub fn call(&self, x: T) -> T {
		(self.function)(x)
	}
	
	pub fn find_zeroes(&self, range: (i32, i32)) -> Vec<T> {
		// default run with a step size of 1/1000
		let domain = make_domain(range.0, range.1, 0.001);
		let mut zeroes: Vec<T> = vec![];
		
		// whether or not the previous call was greater than zero
		let mut g0 = self.call(domain[0].into())>T::from(0.);
		domain.into_iter().map(|x| {
			T::from(x)
		}).for_each(|x| {
			if g0 != (self.call(x) > T::from(0.)) {
				g0 = !g0;
				zeroes.push(x);
			}
		});
		
		zeroes
	}
	
	/// calling this function with an empty vec of roots returns f(x) -> 0
	pub fn polynomial_from_roots(roots: Vec<T>) -> Function<T> {
		let function_roots = roots.into_iter().map(|root| {
			Function::default()-Function::new_t(root)
		}).collect::<Vec<Function<T>>>();
		
		// println!("reached after function_roots: {:?}", function_roots.clone());
		
		match function_roots.len() > 0 {
			true => {
				let mut tmp = Function::new(1.);
				for func in function_roots.into_iter() {
					// println!("func: {:?}", func.clone());
					// println!("tmp: {:?}", tmp.clone());
					tmp = tmp*func;
					// println!("tmp*func: {:?}", tmp.clone());
				}
				// function_roots.into_iter().for_each(|func| {
					// tmp = tmp.clone()*func;
				// });
				// println!("final multiplied function: {:?}", tmp.clone());
				return tmp;
			},
			false => {
				return Function::new(0.);
			}
		}
		
	}
}

impl<T: Rational + 'static> std::fmt::Debug for Function<T> {
	// TODO implement better
	/// Warning this returns nothing
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		// Ok("TO BE IMPLEMENTED");
		// Ok("")
		// write!("f(-5)->{}|f(-4)->{}|f(-3)->{}f(-2)->{}|f(-1)->{}\nf(0)->{}|f(1)->{}|f(2)->{}|f(3)->{}|f(4)->{}|f(5)->{}", )
		write!(
			f,
			"f(-2) {:?}|f(-1) {:?}|f(0) {:?}|f(1) {:?}|f(2) {:?}",
			self.call((-2.).into()),
			self.call((-1.).into()),
			self.call((0.).into()),
			self.call((1.).into()),
			self.call((2.).into()),
		)
	}
}

impl<T: Rational> From<f64> for Function<T> {
	fn from(x: f64) -> Self {
		Self {
			function: Arc::new(move |_x| x.into())
		}
	}
}

impl<T: Rational> Default for Function<T> {
	/// return the function f(x) -> x
	/// or y = x if you want to think of it that way
	fn default() -> Self {
		Self {
			function: Arc::new(|x| x)
		}
	}
}

impl<T: Rational + 'static> Add for Function<T> {
	type Output = Self;
	fn add(self, rhs: Self) -> Self {
		Self { function: Arc::new(move |x| (self.function)(x)+(rhs.function)(x)) }
	}
}

impl<T: Rational + 'static> Sub for Function<T> {
	type Output = Self;
	fn sub(self, rhs: Self) -> Self {
		Self { function: Arc::new(move |x| (self.function)(x)-(rhs.function)(x)) }
	}
}

impl<T: Rational + 'static> Mul for Function<T> {
	type Output = Self;
	fn mul(self, rhs: Self) -> Self {
		Self { function: Arc::new(move |x| (self.function)(x)*(rhs.function)(x)) }
	}
}

impl<T: Rational + 'static> Div for Function<T> {
	type Output = Self;
	fn div(self, rhs: Self) -> Self {
		Self { function: Arc::new(move |x| (self.function)(x)/(rhs.function)(x)) }
	}
}

impl<T: Rational> PartialEq for Function<T> {
	fn eq(&self, rhs: &Self) -> bool {
		let mut roughly_equal = true;
		// check for equality in the range of all integers between -10 and 10
		// may not be the most rigerous but works
		for iter in -10..=10 {
			if (self.function)((iter as f64).into()) != (rhs.function)((iter as f64).into()) {roughly_equal = false;}
		}
		roughly_equal
	}
}


#[cfg(test)]
mod tests {
    use super::*;
    
    // because constant definitions are practically non-functional in rust
    fn define_shit() -> (Function, Function, Function, Function) {
    	return (Function::default(), Function::new(3.), Function::new(5.), Function::from(3.))
    }
    
    fn rounded_eq(a: Vec<f64>, b: Vec<f64>) {
    	let a = a.into_iter().map(|x| {
    		x.round()
    		// (x*1000.).round() / 1000.
    	}).collect::<Vec<f64>>();
    	let b = b.into_iter().map(|x| {
    		x.round()
    		// (x*1000.).round() / 1000.
    	}).collect::<Vec<f64>>();
    	
    	assert_eq!(a, b);
    }
    
    #[test]
    fn polynomial() {
    	assert_eq!(
    		Function::polynomial_from_roots(vec![2., 3.]),
    		(
    			(Function::default()+Function::new(-2.))*
    			(Function::default()+Function::new(-3.))
    		)
    	);
    	assert_eq!(
    		Function::polynomial_from_roots(vec![-2., -1., 3., 5.]),
    		(
    			(Function::default()+Function::new(2.))*
    			(Function::default()+Function::new(1.))*
    			(Function::default()+Function::new(-3.))*
    			(Function::default()+Function::new(-5.))
    		)
    	)
    }
    
    #[test]
    fn test_find_zeroes() {
    	rounded_eq(
    		vec![-1., 1.],
    		Function::polynomial_from_roots(vec![1., -1.]).find_zeroes((-10, 10))
    	);
    	rounded_eq(
    		vec![-3., 2., 5.],
    		Function::polynomial_from_roots(vec![-3., 2., 5.]).find_zeroes((-10, 10))
    	)
    }
		
		#[test]
		fn test_equality() {
			let (y, f ,g , h) = define_shit();
			assert_eq!(
				f,
				h
			);
			assert_eq!(
				Function::from(4.),
				Function::<f64>::new(4.),
			);
			let (y, f ,g , h) = define_shit();
			assert_eq!(
				Function::from(1.)/y.clone(),
				(f/h)/y,
			);
		}
		
		#[test]
		fn test_add() {
			let (y, f ,g , h) = define_shit();
			assert_eq!(
				g+Function::new(4.),
				f+Function::new(6.),
			);
			let (y, f ,g , h) = define_shit();
			assert_eq!(
				f+g.clone(),
				g+h
			);
		}
		
		#[test]
		fn test_sub() {
			let (y, f ,g , h) = define_shit();
			assert_eq!(
				g-h,
				Function::new(2.)
			);
			let (y, f ,g , h) = define_shit();
			assert_eq!(
				f-g,
				Function::new(-2.)
			);
		}
		
		#[test]
		fn test_mul() {
			let (y, f ,g , h) = define_shit();
			assert_eq!(
				g.clone()*h,
				f*g
			);
			let (y, f ,g , h) = define_shit();
			assert_eq!(
				f*g,
				Function::new(15.)
			);
		}
		
		#[test]
		fn test_div() {
			let (y, f ,g , h) = define_shit();
			assert_eq!(
				f/g,
				Function::new(3./5.),
			);
			assert_eq!(
				y/Function::new(1.),
				Function::default()
			);
		}
		
		#[test]
		fn test_call() {
			let (y, f, g, h) = define_shit();
			assert_eq!(
				g.call(2.),
				5.
			);
			assert_eq!(
				h.call(10000.47654),
				3.
			);
			assert_eq!(
				y.call(536.5),
				536.5
			);
		}
}