-
-
Notifications
You must be signed in to change notification settings - Fork 134
/
right_biased.rb
403 lines (366 loc) · 11.5 KB
/
right_biased.rb
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# frozen_string_literal: true
module Dry
module Monads
# A common module for right-biased monads, such as Result/Either, Maybe, and Try.
module RightBiased
# Right part
#
# @api public
module Right
# @private
def self.included(m)
super
def m.to_proc
@to_proc ||= method(:new).to_proc
end
m.singleton_class.alias_method(:call, :new)
end
# Unwraps the underlying value
#
# @return [Object]
def value!
@value
end
# Calls the passed in Proc object with value stored in self
# and returns the result.
#
# If proc is nil, it expects a block to be given and will yield to it.
#
# @example
# Dry::Monads.Right(4).bind(&:succ) # => 5
#
# @param [Array<Object>] args arguments that will be passed to a block
# if one was given, otherwise the first
# value assumed to be a Proc (callable)
# object and the rest of args will be passed
# to this object along with the internal value
# @return [Object] result of calling proc or block on the internal value
def bind(*args, **kwargs)
if args.empty? && !kwargs.empty?
vargs, vkwargs = destructure(@value)
kw = [kwargs.merge(vkwargs)]
else
vargs = [@value]
kw = kwargs.empty? ? EMPTY_ARRAY : [kwargs]
end
if block_given?
yield(*vargs, *args, *kw)
else
obj, *rest = args
obj.(*vargs, *rest, *kw)
end
end
# Does the same thing as #bind except it returns the original monad
# when the result is a Right.
#
# @example
# Dry::Monads.Right(4).tee { Right('ok') } # => Right(4)
# Dry::Monads.Right(4).tee { Left('fail') } # => Left('fail')
#
# @param [Array<Object>] args arguments will be transparently passed through to #bind
# @return [RightBiased::Right]
def tee(...)
bind(...).bind { self }
end
# Abstract method for lifting a block over the monad type.
# Must be implemented for a right-biased monad.
#
# @return [RightBiased::Right]
def fmap(*)
raise NotImplementedError
end
# Ignores arguments and returns self. It exists to keep the interface
# identical to that of {RightBiased::Left}.
#
# @return [RightBiased::Right]
def or(*)
self
end
# Ignores arguments and returns self. It exists to keep the interface
# identical to that of {RightBiased::Left}.
#
# @param _alt [RightBiased::Right, RightBiased::Left]
#
# @return [RightBiased::Right]
def |(_alt)
self
end
# A lifted version of `#or`. For {RightBiased::Right} acts in the same way as `#or`,
# that is returns itselt.
#
# @return [RightBiased::Right]
def or_fmap(*)
self
end
# Returns value. It exists to keep the interface identical to that of RightBiased::Left
#
# @return [Object]
def value_or(_val = nil)
@value
end
# Applies the stored value to the given argument if the argument has type of Right,
# otherwise returns the argument.
#
# @example happy path
# create_user = Dry::Monads::Success(CreateUser.new)
# name = Success("John")
# create_user.apply(name) # equivalent to CreateUser.new.call("John")
#
# @example unhappy path
# name = Failure(:name_missing)
# create_user.apply(name) # => Failure(:name_missing)
#
# @return [RightBiased::Left,RightBiased::Right]
def apply(val = Undefined, &block)
unless @value.respond_to?(:call)
raise TypeError, "Cannot apply #{val.inspect} to #{@value.inspect}"
end
Undefined.default(val, &block).fmap { curry.(_1) }
end
# @param other [Object]
# @return [Boolean]
def ===(other)
other.instance_of?(self.class) && value! === other.value!
end
# Maps the value to Dry::Monads::Unit, useful when you don't care
# about the actual value.
#
# @example
# Dry::Monads::Success(:success).discard
# # => Success(Unit)
#
# @return [RightBiased::Right]
def discard
fmap { Unit }
end
# Removes one level of monad structure by joining two values.
#
# @example
# include Dry::Monads::Result::Mixin
# Success(Success(5)).flatten # => Success(5)
# Success(Failure(:not_a_number)).flatten # => Failure(:not_a_number)
# Failure(:not_a_number).flatten # => Failure(:not_a_number)
#
# @return [RightBiased::Right,RightBiased::Left]
def flatten
bind(&:itself)
end
# Combines the wrapped value with another monadic value.
# If both values are right-sided, yields a block and passes a tuple
# of values there. If no block given, returns a tuple of values wrapped with
# a monadic structure.
#
# @example
# include Dry::Monads::Result::Mixin
#
# Success(3).and(Success(5)) # => Success([3, 5])
# Success(3).and(Failure(:not_a_number)) # => Failure(:not_a_number)
# Failure(:not_a_number).and(Success(5)) # => Failure(:not_a_number)
# Success(3).and(Success(5)) { |a, b| a + b } # => Success(8)
#
# @param mb [RightBiased::Left,RightBiased::Right]
#
# @return [RightBiased::Left,RightBiased::Right]
def and(mb)
bind do |a|
mb.fmap do |b|
if block_given?
yield([a, b])
else
[a, b]
end
end
end
end
# Pattern matching
#
# @example
# case Success(x)
# in Success(Integer) then ...
# in Success(2..100) then ...
# in Success(2..200 => code) then ...
# end
#
# @api private
def deconstruct
if Unit.equal?(@value)
EMPTY_ARRAY
elsif !@value.is_a?(::Array)
[@value]
else
@value
end
end
# Pattern matching hash values
#
# @example
# case Success(x)
# in Success(code: 200...300) then :ok
# in Success(code: 300...400) then :redirect
# in Success(code: 400...500) then :user_error
# in Success(code: 500...600) then :server_error
# end
#
# @api private
def deconstruct_keys(keys)
if @value.respond_to?(:deconstruct_keys)
@value.deconstruct_keys(keys)
else
EMPTY_HASH
end
end
private
# @api private
def destructure(value)
if value.is_a?(::Hash)
[EMPTY_ARRAY, value]
else
[[value], EMPTY_HASH]
end
end
# @api private
def curry
@curried ||= Curry.(@value)
end
end
# Left/wrong/erroneous part
#
# @api public
module Left
# @private
# @return [String] Caller location
def self.trace_caller
caller_locations(2, 1)[0].to_s
end
# Raises an error on accessing internal value
def value!
raise UnwrapError, self
end
# Ignores the input parameter and returns self. It exists to keep the interface
# identical to that of {RightBiased::Right}.
#
# @return [RightBiased::Left]
def bind(*)
self
end
# Ignores the input parameter and returns self. It exists to keep the interface
# identical to that of {RightBiased::Right}.
#
# @return [RightBiased::Left]
def tee(*)
self
end
# Ignores the input parameter and returns self. It exists to keep the interface
# identical to that of {RightBiased::Right}.
#
# @return [RightBiased::Left]
def fmap(*)
self
end
# Left-biased #bind version.
#
# @example
# Dry::Monads.Left(ArgumentError.new('error message')).or(&:message) # => "error message"
# Dry::Monads.None.or('no value') # => "no value"
# Dry::Monads.None.or { Time.now } # => current time
#
# @return [Object]
def or(*)
raise NotImplementedError
end
# Returns the passed value. Works in pair with {RightBiased::Right#|}.
#
# @param alt [RightBiased::Right, RightBiased::Left]
#
# @return [RightBiased::Right, RightBiased::Left]
def |(alt)
self.or(alt)
end
# A lifted version of `#or`. This is basically `#or` + `#fmap`.
#
# @example
# Dry::Monads.None.or_fmap('no value') # => Some("no value")
# Dry::Monads.None.or_fmap { Time.now } # => Some(current time)
#
# @return [RightBiased::Left, RightBiased::Right]
def or_fmap(*)
raise NotImplementedError
end
# Returns the passed value
#
# @return [Object]
def value_or(val = nil)
if block_given?
yield
else
val
end
end
# Ignores the input parameter and returns self. It exists to keep the interface
# identical to that of {RightBiased::Right}.
#
# @return [RightBiased::Left]
def apply(*)
self
end
# Returns self back. It exists to keep the interface
# identical to that of {RightBiased::Right}.
#
# @return [RightBiased::Left]
def discard
self
end
# Returns self back. It exists to keep the interface
# identical to that of {RightBiased::Right}.
#
# @return [RightBiased::Left]
def flatten
self
end
# Returns self back. It exists to keep the interface
# identical to that of {RightBiased::Right}.
#
# @return [RightBiased::Left]
def and(_)
self
end
# Pattern matching
#
# @example
# case Success(x)
# in Success(Integer) then ...
# in Success(2..100) then ...
# in Success(2..200 => code) then ...
# in Failure(_) then ...
# end
#
# @api private
def deconstruct
if Unit.equal?(@value)
[]
elsif @value.is_a?(::Array)
@value
else
[@value]
end
end
# Pattern matching hash values
#
# @example
# case Failure(x)
# in Failure(code: 400...500) then :user_error
# in Failure(code: 500...600) then :server_error
# end
#
# @api private
def deconstruct_keys(keys)
if @value.respond_to?(:deconstruct_keys)
@value.deconstruct_keys(keys)
else
EMPTY_HASH
end
end
end
end
end
end