Skip to content

Commit 8303b2b

Browse files
committed
Abstract type example
Add example of using abstract hashmap_type for procedure interrface.
1 parent b1dab28 commit 8303b2b

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

example/hashmaps/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
ADD_EXAMPLE(hashmaps_abstract_type)
12
ADD_EXAMPLE(hashmaps_calls)
23
ADD_EXAMPLE(hashmaps_copy_key)
34
ADD_EXAMPLE(hashmaps_entries)
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
! For procedure interfaces, consider using abstract hashmap_type for interface definition.
3+
! This allows the procedure to be used for both chaining and open hashmap types.
4+
5+
program example_abstract_type
6+
use stdlib_kinds, only: int8, int64
7+
use stdlib_hashmaps, only: chaining_hashmap_type, open_hashmap_type, hashmap_type
8+
9+
implicit none
10+
11+
integer :: out_value
12+
type(chaining_hashmap_type) :: chaining_map
13+
type(open_hashmap_type) :: open_map
14+
15+
! Chaining map call
16+
call put_int(chaining_map, '1', 1)
17+
call get_int(chaining_map, '1', out_value)
18+
print *, "Chaining out value is ", out_value
19+
20+
! Open map call
21+
call put_int(open_map, '1', 1)
22+
call get_int(open_map, '1', out_value)
23+
print *, "Open out value is ", out_value
24+
25+
contains
26+
27+
subroutine put_int(map, key, value)
28+
class(hashmap_type), intent(inout) :: map
29+
character(len=*), intent(in) :: key
30+
integer, intent(in) :: value
31+
32+
call map%map_entry(key, value)
33+
end subroutine put_int
34+
35+
36+
subroutine get_int(map, key, value)
37+
class(hashmap_type), intent(inout) :: map
38+
character(len=*), intent(in) :: key
39+
integer, intent(out) :: value
40+
class(*), allocatable :: data
41+
42+
call map%get_other_data( key, data)
43+
44+
select type (data)
45+
type is (integer)
46+
value = data
47+
class default
48+
print *, 'Invalid data type in other'
49+
end select
50+
end subroutine get_int
51+
52+
53+
end program example_abstract_type

0 commit comments

Comments
 (0)