-
Notifications
You must be signed in to change notification settings - Fork 47
/
compress_jm_iter_steps.rye
76 lines (65 loc) · 1.57 KB
/
compress_jm_iter_steps.rye
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
; Translation of simple Compression puzzle to Ryelang
; Mitja's Golang iterative solution
; https://github.com/otobrglez/compression-puzzle/blob/master/src/go/compress_mitja.go
;
;func compress(in string) (out string) {
; if len(in) == 0 {
; return ""
; }
; ch := rune(in[0])
; count := 0
; for _, cur := range in {
; if cur == ch {
; count++
; continue
; }
; out = out + fmt.Sprint(count) + string(ch)
; ch = cur
; count = 1
; }
; out = out + fmt.Sprint(count) + string(ch)
; return
;}
; Direct translation to Rye
compress-a: fn { in } {
if in .length = 0 {
return ""
}
chr: first in
cnt: 0 , out: ""
for in { :cur
either cur = chr {
cnt: cnt + 1
} {
out: out + cnt .str + chr
chr: cur
cnt: 1
}
}
out: out + cnt .str + chr
}
"AAABBACCC" .compress-a .assert-equal "3A2B1A3C"
; Some cleaning up
compress-b: fn { in } {
chr: first in |^fix "" ; "returning function" fix returns to caller in case arg is a failure
cnt: 0 , out: ""
for in {
:cur = chr |either { ; we can set cur inline
inc! 'cnt ; rye has few functions that change data in-place. To warn you the end w/ !
} {
append! cnt .str + chr 'out ; we use in-place append!
chr: cur , cnt: 1
}
}
append! cnt .str + chr 'out
}
"AAABBACCC" .compress-b .assert-equal "3A2B1A3C"
; Final version
compress: fn1 {
|pass { .first |fix "" :chr , cnt: 0 , out: ""
output: { cnt .concat chr |append! 'out } }
|for { = chr |either { inc! 'cnt }
{ do output , cnt: 1 } , :chr
} do output
}
"AAABBACCC" .compress .assert-equal "3A2B1A3C"