Skip to content

Commit b1d52b9

Browse files
authored
Merge pull request #58 from termoshtt/into_real
Convert f64 to Scalar
2 parents 4204a51 + df6d333 commit b1d52b9

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

src/types.rs

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,18 +35,50 @@ pub trait Scalar
3535
+ Conjugate
3636
+ RandNormal
3737
+ Debug {
38+
fn from_f64(f64) -> Self;
3839
}
3940

40-
impl Scalar for f32 {}
41-
impl Scalar for f64 {}
42-
impl Scalar for c32 {}
43-
impl Scalar for c64 {}
41+
impl Scalar for f32 {
42+
fn from_f64(f: f64) -> Self {
43+
f as f32
44+
}
45+
}
4446

45-
pub trait RealScalar: Scalar + Float + Sum {}
47+
impl Scalar for f64 {
48+
fn from_f64(f: f64) -> Self {
49+
f
50+
}
51+
}
52+
53+
impl Scalar for c32 {
54+
fn from_f64(f: f64) -> Self {
55+
Self::new(f as f32, 0.0)
56+
}
57+
}
4658

59+
impl Scalar for c64 {
60+
fn from_f64(f: f64) -> Self {
61+
Self::new(f, 0.0)
62+
}
63+
}
64+
65+
pub trait RealScalar: Scalar + Float + Sum {}
4766
impl RealScalar for f32 {}
4867
impl RealScalar for f64 {}
4968

69+
/// Convert `f64` into `Scalar`
70+
///
71+
/// ```rust
72+
/// use ndarray_linalg::*;
73+
/// fn mult<A: Scalar>(a: A) -> A {
74+
/// // a * 2.0 // Error!
75+
/// a * into_scalar(2.0)
76+
/// }
77+
/// ```
78+
pub fn into_scalar<T: Scalar>(f: f64) -> T {
79+
T::from_f64(f)
80+
}
81+
5082
/// Define associating real float type
5183
pub trait AssociatedReal: Sized {
5284
type Real: RealScalar;

0 commit comments

Comments
 (0)