# How can I implement this?

**URL:** https://discourse.myhdl.org/t/how-can-i-implement-this/416
**Category:** Support
**Created:** [March 2, 2020, 12:11pm UTC](https://discourse.myhdl.org/t/how-can-i-implement-this/416 "2020-03-02T12:11:37Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![krs](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.myhdl.org/krs/32/121_2.png) [@krs](https://discourse.myhdl.org/u/krs)
#### Post date: [March 2, 2020, 12:11pm UTC](https://discourse.myhdl.org/t/how-can-i-implement-this/416/1 "2020-03-02T12:11:37Z")

</div>

Hello I would like to implement the following logic with a for loop in myhdl.  
Can anyone tell me how to do it ? Thanks

```
intMux = [Signal(intbv(0)[16:]) for i in range(8)]
@always(reset.posedge, clk.posedge)
def statsGen():
  if reset == 1 :
    sumInt.next = 0
  elif (vld == 1):
    sumInt.next = sumInt + intMux[0] + intMux[1] + intMux[2] + \
    intMux[3] + intMux[4] + intMux[5] + intMux[6] + intMux[7]
```

---

<div class="post-metadata">

### Author: ![JanCoombs](https://avatars.discourse-cdn.com/v4/letter/j/9fc29f/32.png) [@JanCoombs](https://discourse.myhdl.org/u/JanCoombs)
#### Post date: [March 2, 2020, 5:49pm UTC](https://discourse.myhdl.org/t/how-can-i-implement-this/416/2 "2020-03-02T17:49:47Z")

</div>

> [@krs](#):
>
> Hello I would like to implement the following logic with a for loop in myhdl.  
> Can anyone tell me how to do it ? Thanks

```
@always(reset.posedge, clk.posedge)
def statsGen():
    if (reset == 1):	sumInt.next = 0
    elif (vld == 1):
	sumVar = 0
	for ii in range( AddendCount ):
		sumVar = sumVar + intMux[ii] 
	sumInt.next = sumVar

```

Jan Coombs

---

<div class="post-metadata">

### Author: ![josyb](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.myhdl.org/josyb/32/5_2.png) [@josyb](https://discourse.myhdl.org/u/josyb)
#### Post date: [March 3, 2020, 8:57pm UTC](https://discourse.myhdl.org/t/how-can-i-implement-this/416/3 "2020-03-03T20:57:07Z")

</div>

My take on this:

```python
def sum(a):
    if len(a) > 2:
        # split in two
        n = len(a) // 2
        return sum(a[:n]) + sum(a[n:])
    elif len(a) == 2:
        return a[0] + a[1]
    else:
        return a[0]

intMux = [Signal(intbv(0)[16:]) for __ in range(8)]

@always_seq(clk.posedge, reset)
def statsgen():
    if vld:
        sumInt.next = sum(intMux)

```

This implements a _binary tree_-like circuit, and will give you the fastest implementation in hardware.
