Sha256: 444281ad149a3b8bc92224eb4264afb00f911f13cd72cf37b758896cfbe1d1f4

Contents?: true

Size: 936 Bytes

Versions: 1

Compression:

Stored size: 936 Bytes

Contents

require 'kleisli'

module Dry
  module Data
    def self.SumType(left, right)
      klass =
        if left.primitive == NilClass
          SumType::Optional
        else
          SumType
        end
      klass.new(left, right)
    end

    class SumType
      attr_reader :left

      attr_reader :right

      class Optional < SumType
        def call(input)
          Maybe(super(input))
        end
        alias_method :[], :call
      end

      def initialize(left, right)
        @left, @right = left, right
      end

      def name
        [left, right].map(&:name).join(' | ')
      end

      def call(input)
        result = left[input]

        if left.valid?(result)
          result
        else
          right[input]
        end
      rescue TypeError
        right[input]
      end
      alias_method :[], :call

      def valid?(input)
        left.valid?(input) || right.valid?(input)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dry-data-0.1.0 lib/dry/data/sum_type.rb