-
Notifications
You must be signed in to change notification settings - Fork 1
/
compound.gleam
64 lines (51 loc) · 1.25 KB
/
compound.gleam
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
import gleam/httpc
import gleam/http/request
import gleam/result
import gleam/dict.{type Dict}
import gleam/dynamic.{dict, string, int}
import gleam/json
const nimi_pona = "https://nimi.pona.la/en-tp.json"
pub type CompoundFetcher {
CompoundFetcher(
english: String
)
}
pub type CompoundError {
DynamicError(dynamic.Dynamic)
WordNotFound(String)
}
pub type Compound {
Compound(
word: String,
definitions: Dict(String, Int)
)
}
pub fn compound(english: String) -> CompoundFetcher {
CompoundFetcher(
english
)
}
pub fn fetch(fetcher: CompoundFetcher) -> Result(Compound, CompoundError) {
let assert Ok(req) =
request.to(nimi_pona)
let resp =
result.replace_error(httpc.send(req), DynamicError)
let body = case resp {
Ok(resp) -> resp.body
Error(_) -> "{}"
}
let data_decoder = dict(string, dict(string, int))
let data =
json.decode(from: body, using: data_decoder)
|> result.unwrap(dict.new())
let result =
data
|> dict.get(fetcher.english)
case result {
Ok(definitions) -> Ok(Compound(fetcher.english, definitions))
Error(_) -> Error(WordNotFound("Word not found:" <> fetcher.english))
}
}
pub fn get_definitions(compound: Compound) -> Dict(String, Int) {
compound.definitions
}