I have just one question
I wrote an example here
package main
import (
"fmt"
)
type PACK struct {
d, r int
}
func main() {
st := &PACK{}
st.d, st.r = f(12, 32)
}
func f(a, b int) (d int, r int) {
d = a / b
r = a ^ b
return
}
So, the question is - how can i make thing like this
st := &PACK{ f(1,2) }
I want my function return arguments to be a struct initializer!
You cannot do this, it is not possible.
You can create a method on struct Pack, that will initialize the values. For example:
package main
import "fmt"
type Pack struct {
d, r int
}
func (p *Pack) init (a, b int) {
p.d = a / b
p.r = a ^ b
}
func main() {
pack := Pack{} // d and r are initialized to 0 here
pack.init(10, 4)
fmt.Println(pack)
}
Result:
{2 14}
goplayground
Related
The nim lang tutorial here says -
A procedure that does not have any return statement and does not use the special result variable returns the value of its last expression.
Why does my echo res print 0 ? Shouldn't I expect the last statement a mod b (= 3) to be returned?
proc divmod(a, b: int; res, remainder: var int): int =
res = a div b
remainder = a mod b
var
x, y: int
let res: int = divmod(8, 5, x, y) # modifies x and y
echo res
In your divmod proc remainder = a mod b is a statement, not an expression, so divmod returns the default value for int which is 0.
I'm not sure why'd you want to both return remainder by a mutable argument and the result, but this is how you can do it:
proc divmod(a, b: int; res, remainder: var int): int =
res = a div b
remainder = a mod b
remainder # or result = remainder
var
x, y: int
let res: int = divmod(8, 5, x, y) # modifies x and y
echo res
This is how your proc can be remade if you don't really need to modify existing values:
proc divmod(a, b: int): (int, int) =
(a div b, a mod b)
let (x, y) = divmod(8, 5)
echo x, " ", y
This question already has an answer here:
Is it possible to automatically implement a trait for any tuple that is made up of types that all implement the trait?
(1 answer)
Closed 3 years ago.
I have a trait like this:
trait Foo {
fn do_something(self) -> Self;
}
And I want implement this trait for a tuple that may have any number of elements that implement this trait.
impl<T> Foo for (T, T) where T: Foo {
fn do_something(self) -> Self {
let (t0, t1) = self;
(t0.do_something(), t1.do_something())
}
}
impl<T> Foo for (T, T, T) where T: Foo {
fn do_something(self) -> Self {
let (t0, t1, t2) = self;
(t0.do_something(), t1.do_something(), t2.do_something())
}
}
// and so on...
Note: I'm not sure whether you should do this, but here's a way to anyway. (Feels hacky to me, and that may be because I don't know how to make a better macro.)
Homogeneous tuples (T, T)
The way you've described it:
impl<T> Foo for (T, T) where T: Foo
Here, the entire tuple must be homogeneous (i.e. (MyType, MyType2).do_something() will not work because of monomorphization).
This raises a flag because tuples are for heterogeneous data.
If implementing the trait only one homogeneous tuples is still what you want, we can implement a macro the way the standard library does to implement traits for varied length tuples, with some modifications. (Click src on the right of an impl to see it's source.)
macro_rules! replace_expr {
($_t:tt $sub:ty) => {$sub};
}
macro_rules! tuple_impls {
( $( $name:ident )+ ) => {
impl<T: Foo> Foo for ($(replace_expr!(($name) T),)+)
{
fn do_something(self) -> Self {
let ($($name,)+) = self;
($($name.do_something(),)+)
}
}
};
}
tuple_impls! { A }
tuple_impls! { A B }
tuple_impls! { A B C }
tuple_impls! { A B C D }
tuple_impls! { A B C D E }
tuple_impls! { A B C D E F }
tuple_impls! { A B C D E F G }
tuple_impls! { A B C D E F G H }
tuple_impls! { A B C D E F G H I }
tuple_impls! { A B C D E F G H I J }
tuple_impls! { A B C D E F G H I J K }
tuple_impls! { A B C D E F G H I J K L }
Playground
Heterogeneous tuples (T1, T2)
If you're okay with (MyType, MyType2).do_something() working (where both implement the Foo trait), you can try this simpler macro:
macro_rules! tuple_impls {
( $( $name:ident )+ ) => {
impl<$($name: Foo),+> Foo for ($($name,)+)
{
fn do_something(self) -> Self {
let ($($name,)+) = self;
($($name.do_something(),)+)
}
}
};
}
tuple_impls! { A }
tuple_impls! { A B }
tuple_impls! { A B C }
tuple_impls! { A B C D }
tuple_impls! { A B C D E }
tuple_impls! { A B C D E F }
tuple_impls! { A B C D E F G }
tuple_impls! { A B C D E F G H }
tuple_impls! { A B C D E F G H I }
tuple_impls! { A B C D E F G H I J }
tuple_impls! { A B C D E F G H I J K }
tuple_impls! { A B C D E F G H I J K L }
Playground
No. (unless you are ready to use macros - see other answers)
Tuples in Rust have a fixed length just like arrays. I do not believe you can express the concept of "tuples of any length".
In other words a tuple of 2 elements is a different compound type than a tuple of 3 elements. If you insist on using tuples you have to go for the solution you outlined above.
Use a collection? (such as aliasing an existing one and implementing the trait on it)?
I am new to Haskel and want to learn it. I want to print intermediate value in recursive function in haskell but i am stuck in parse error on input "=" on line b= b+50.
`main' t s a b c
| t > s = 0
| otherwise = do
print a
print b
print c
b = b + 50
c = b + 2 * a
main' (t+1) s (a+1) b c `
the C equivalent for this code is
int calculate(t,s,a,b,c)
{
printf( "%d,%d,%d",a,b,c);
if(t > s)
return 0;
else
{
b = b + 50;
c = b + 2 * a;
return calculate (t+1,s,a,b,c);
}
}
int main()
{
calculate(0,10,2,6,7);
return 0;
}`
Please help me to resolve this problem. It is not so difficult to do in C but I could not figure out how to do it in Haskel.
As PyRulez says in his comment, you need to use let syntax in do blocks. However, you are also going to run into issues because your function parameters, like all values in Haskell, are immutable. You will need to do something like:
let b' = b + 5
let c' = b' + 2 * a
If you only want to print some intermediate value, you don't need to have your function in the IO world:
you can use the Debug.Trace module:
import Debug.Trace
func :: Int -> Int -> Int -> Int -> Int
func 0 _ _ _ = 0
func t a b c = trace ("a="++(show a)++" b="++(show b)++" c="++(show c)) $ recurs
where recurs = func (t-1) (a+1) (b+50) (b+2*a)
it gives me:
> func 5 1 1 1
a=1 b=1 c=1
a=2 b=51 c=3
a=3 b=101 c=55
a=4 b=151 c=107
a=5 b=201 c=159
Let's say I have the following record ADT:
data Foo = Bar { a :: Integer, b :: String, c :: String }
I want a function that takes a record and returns a record (of the same type) where all but one of the fields have identical values to the one passed as argument, like so:
walkDuck x = Bar { a = a x, b = b x, c = lemonadeStand (a x) (b x) }
The above works, but for a record with more fields (say 10), creating a such function would entail a lot of typing that I feel is quite unnecessary.
Are there any less tedious ways of doing the same?
Yes, there's a nice way of updating record fields. In GHCi you can do --
> data Foo = Foo { a :: Int, b :: Int, c :: String } -- define a Foo
> let foo = Foo { a = 1, b = 2, c = "Hello" } -- create a Foo
> let updateFoo x = x { c = "Goodbye" } -- function to update Foos
> updateFoo foo -- update the Foo
Foo {a = 1, b = 2, c = "Goodbye" }
This is a good job for lenses:
data Foo = Foo { a :: Int, b :: Int , c :: String }
test = Foo 1 2 "Hello"
Then:
setL c "Goodbye" test
would update field 'c' of 'test' to your string.
You don’t need to define auxiliary functions or employ lenses. Standard Haskell has already what you need. Let’s take the example by Don Stewart:
data Foo = Foo { a :: Int, b :: Int , c :: String }
test = Foo 1 2 "Hello"
Then you can just say test { c = "Goodbye" } to get an updated record.
Is there a way to use functions in Discriminated Unions? I am looking to do something like this:
Type Test<'a> = Test of 'a-> bool
I know this is possible in Haskell using newtype and I was wondering what the equivalent in F# would be.
Thanks.
type Test<'A> = Test of ('A -> bool)
As an expansion on desco's answer you can apply the function tucked into Test with pattern matching:
type Test<'a> = Test of ('a -> bool)
// let applyTest T x = match T with Test(f) -> f x
// better: (as per kvb's comment) pattern match the function argument
let applyTest (Test f) x = f x
Example:
// A Test<string>
let upperCaseTest = Test (fun (s:string) -> s.ToUpper() = s)
// A Test<int>
let primeTest =
Test (fun n ->
let upper = int (sqrt (float n))
n > 1 && (n = 2 || [2..upper] |> List.forall (fun d -> n%d <> 0))
)
In FSI:
> applyTest upperCaseTest "PIGSMIGHTFLY";;
val it : bool = true
> applyTest upperCaseTest "PIGSMIgHTFLY";;
val it : bool = false
> [1..30] |> List.filter (applyTest primeTest);;
val it : int list = [2; 3; 5; 7; 11; 13; 17; 19; 23; 29]