This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
- C#
- D
- Dart
- Fortran
- Go
- Go
- Groovy
- Haskell
- Haskell
- JS
- Java
- Java
- Java
- Kotlin
- Lua
- PHP
- Perl
- Python
- Ruby
- Rust
- Scheme
module x
type tree
type (tree), pointer :: left, right
contains
procedure, pass:: trav
end type tree
contains
recursive subroutine trav (t, f)
class (tree), intent(inout) :: t
interface
subroutine f(t)
import
class (tree), intent(inout) :: t
end subroutine f
end interface
if (associated (t%left)) call trav (t%left, f)
call f(t)
if (associated (t%right)) call trav (t%right, f)
end subroutine trav
end module x
func (bt *BinTree[L]) Dfs(f func(*BinTree[L])) {
if bt == nil {
return
}
bt.Left.Dfs(f)
f(bt)
bt.Right.Dfs(f)
}
The type parameter L is for arbitrary node label data
func (bt *BinTree) Dfs(f func(*BinTree)) {
if bt == nil {
return
}
bt.Left.Dfs(f)
f(bt)
bt.Right.Dfs(f)
}
The function f is a parameter of the traversal method Dfs.
It's legit to call a method on a nil receiver, and useful to make code more concise with less checks for nil.
It's legit to call a method on a nil receiver, and useful to make code more concise with less checks for nil.
class BinTree {
BinTree left
BinTree right
void dfs(Closure f) {
left?.dfs(f)
f.call(this)
right?.dfs(f)
}
}
Closure can execute on values in BinTree
fn depthFirstTraverse<T>(bt: &mut BiTree<T>, f: fn(&mut BiTree<T>)) {
if let Some(left) = &mut bt.left {
depthFirstTraverse(left, f);
}
f(bt);
if let Some(right) = &mut bt.right {
depthFirstTraverse(right, f);
}
}
programming-idioms.org