Saltar al contenido

Paquete Types

El paquete github.com/gofhir/fhirpath/types define el sistema de tipos FHIRPath. Cada valor retornado por una evaluación FHIRPath es un Value, y cada resultado de evaluación es una Collection (un slice ordenado de Value). Esta página documenta todas las interfaces, tipos y sus métodos.

import "github.com/gofhir/fhirpath/types"

Interfaces Principales

Value

La interfaz base para todos los valores FHIRPath. Cada tipo en este paquete implementa Value.

type Value interface {
    // Type returns the FHIRPath type name (e.g., "Boolean", "Integer", "String").
    Type() string

    // Equal compares exact equality (the = operator in FHIRPath).
    Equal(other Value) bool

    // Equivalent compares equivalence (the ~ operator in FHIRPath).
    // For strings: case-insensitive, normalized whitespace.
    Equivalent(other Value) bool

    // String returns a human-readable string representation of the value.
    String() string

    // IsEmpty indicates if this value represents an empty value.
    IsEmpty() bool
}

Comparable

Implementada por tipos que soportan ordenamiento (menor que, mayor que). Extiende Value.

type Comparable interface {
    Value
    // Compare returns -1 if less than, 0 if equal, 1 if greater than.
    // Returns error if types are incompatible.
    Compare(other Value) (int, error)
}

Tipos que implementan Comparable: Integer, Decimal, String, Date, DateTime, Time, Quantity.

Numeric

Implementada por tipos numéricos. Proporciona una conversión a Decimal para aritmética entre tipos.

type Numeric interface {
    Value
    // ToDecimal converts the numeric value to a Decimal.
    ToDecimal() Decimal
}

Tipos que implementan Numeric: Integer, Decimal.


Collection

Collection es el tipo de retorno fundamental para todas las expresiones FHIRPath. Es una secuencia ordenada de elementos Value.

type Collection []Value

Métodos de Consulta

Empty

Retorna true si la colección no tiene elementos.

func (c Collection) Empty() bool

Count

Retorna el número de elementos.

func (c Collection) Count() int

First

Retorna el primer elemento y true, o nil y false si la colección está vacía.

func (c Collection) First() (Value, bool)

Last

Retorna el último elemento y true, o nil y false si la colección está vacía.

func (c Collection) Last() (Value, bool)

Single

Retorna el único elemento si la colección tiene exactamente un elemento. Retorna un error si la colección está vacía o tiene más de un elemento.

func (c Collection) Single() (Value, error)

Contains

Retorna true si la colección contiene un valor igual a v (usando Equal).

func (c Collection) Contains(v Value) bool

Métodos de Subconjunto

Tail

Retorna todos los elementos excepto el primero.

func (c Collection) Tail() Collection

Skip

Retorna una nueva colección con los primeros n elementos eliminados.

func (c Collection) Skip(n int) Collection

Take

Retorna una nueva colección con solo los primeros n elementos.

func (c Collection) Take(n int) Collection

Operaciones de Conjunto

Distinct

Retorna una nueva colección con valores duplicados eliminados, preservando el orden de la primera aparición.

func (c Collection) Distinct() Collection

IsDistinct

Retorna true si todos los elementos de la colección son únicos.

func (c Collection) IsDistinct() bool

Union

Retorna la unión de dos colecciones con duplicados eliminados.

func (c Collection) Union(other Collection) Collection

Combine

Retorna una nueva colección que concatena ambas colecciones. A diferencia de Union, los duplicados se preservan.

func (c Collection) Combine(other Collection) Collection

Intersect

Retorna los elementos que existen en ambas colecciones.

func (c Collection) Intersect(other Collection) Collection

Exclude

Retorna los elementos en c que no están en other.

func (c Collection) Exclude(other Collection) Collection

Agregación Boolean

AllTrue

Retorna true si cada elemento es un Boolean con valor true. Retorna true para una colección vacía (verdad vacua).

func (c Collection) AllTrue() bool

AnyTrue

Retorna true si al menos un elemento es un Boolean con valor true.

func (c Collection) AnyTrue() bool

AllFalse

Retorna true si cada elemento es un Boolean con valor false. Retorna true para una colección vacía.

func (c Collection) AllFalse() bool

AnyFalse

Retorna true si al menos un elemento es un Boolean con valor false.

func (c Collection) AnyFalse() bool

Conversión

ToBoolean

Convierte una colección singleton Boolean a un bool de Go. Retorna un error si la colección está vacía, tiene más de un elemento, o el único elemento no es un Boolean.

func (c Collection) ToBoolean() (bool, error)

String

Retorna una representación en cadena de la colección en la forma [val1, val2, ...].

func (c Collection) String() string

Ejemplo de Collection

import "github.com/gofhir/fhirpath/types"

c := types.Collection{
    types.NewString("alpha"),
    types.NewString("beta"),
    types.NewString("gamma"),
}

fmt.Println(c.Count())       // 3
fmt.Println(c.Empty())       // false

first, ok := c.First()
fmt.Println(first, ok)       // alpha true

tail := c.Tail()
fmt.Println(tail)            // [beta, gamma]

top2 := c.Take(2)
fmt.Println(top2)            // [alpha, beta]

without1 := c.Skip(1)
fmt.Println(without1)        // [beta, gamma]

single, err := c.Take(1).Single()
fmt.Println(single, err)     // alpha <nil>

Boolean

Representa un valor booleano FHIRPath (true o false).

type Boolean struct {
    // unexported fields
}

Implementa: Value

NewBoolean

func NewBoolean(v bool) Boolean

Métodos Principales

MétodoFirmaDescripción
Boolfunc (b Boolean) Bool() boolRetorna el valor bool subyacente
Notfunc (b Boolean) Not() BooleanRetorna la negación lógica
Typefunc (b Boolean) Type() stringRetorna "Boolean"
Stringfunc (b Boolean) String() stringRetorna "true" o "false"

Ejemplo:

t := types.NewBoolean(true)
f := t.Not()

fmt.Println(t.Bool())   // true
fmt.Println(f.Bool())   // false
fmt.Println(t.Type())   // Boolean
fmt.Println(t.Equal(f)) // false

Integer

Representa un valor entero FHIRPath (respaldado por int64).

type Integer struct {
    // unexported fields
}

Implementa: Value, Comparable, Numeric

NewInteger

func NewInteger(v int64) Integer

Métodos Principales

MétodoFirmaDescripción
Valuefunc (i Integer) Value() int64Retorna el int64 subyacente
ToDecimalfunc (i Integer) ToDecimal() DecimalConvierte a Decimal
Addfunc (i Integer) Add(other Integer) IntegerSuma
Subtractfunc (i Integer) Subtract(other Integer) IntegerResta
Multiplyfunc (i Integer) Multiply(other Integer) IntegerMultiplicación
Dividefunc (i Integer) Divide(other Integer) (Decimal, error)División (retorna Decimal)
Divfunc (i Integer) Div(other Integer) (Integer, error)División entera
Modfunc (i Integer) Mod(other Integer) (Integer, error)Módulo
Negatefunc (i Integer) Negate() IntegerNegación
Absfunc (i Integer) Abs() IntegerValor absoluto
Powerfunc (i Integer) Power(exp Integer) DecimalExponenciación (retorna Decimal)
Sqrtfunc (i Integer) Sqrt() (Decimal, error)Raíz cuadrada (retorna Decimal)
Comparefunc (i Integer) Compare(other Value) (int, error)Comparación (funciona con Integer y Decimal)

Ejemplo:

a := types.NewInteger(10)
b := types.NewInteger(3)

fmt.Println(a.Add(b).Value())       // 13
fmt.Println(a.Subtract(b).Value())  // 7
fmt.Println(a.Multiply(b).Value())  // 30

div, _ := a.Div(b)
fmt.Println(div.Value())            // 3

mod, _ := a.Mod(b)
fmt.Println(mod.Value())            // 1

result, _ := a.Divide(b)
fmt.Println(result)                 // 3.3333333333333333

Decimal

Representa un valor decimal FHIRPath con precisión arbitraria (respaldado por github.com/shopspring/decimal).

type Decimal struct {
    // unexported fields
}

Implementa: Value, Comparable, Numeric

Constructores

FunciónFirmaDescripción
NewDecimalfunc NewDecimal(s string) (Decimal, error)Crea desde una cadena como "3.14"
NewDecimalFromIntfunc NewDecimalFromInt(v int64) DecimalCrea desde un int64
NewDecimalFromFloatfunc NewDecimalFromFloat(v float64) DecimalCrea desde un float64
MustDecimalfunc MustDecimal(s string) DecimalComo NewDecimal, genera panic en caso de error

Métodos Principales

MétodoFirmaDescripción
Valuefunc (d Decimal) Value() decimal.DecimalRetorna el decimal.Decimal subyacente
ToDecimalfunc (d Decimal) ToDecimal() DecimalSe retorna a sí mismo
Addfunc (d Decimal) Add(other Decimal) DecimalSuma
Subtractfunc (d Decimal) Subtract(other Decimal) DecimalResta
Multiplyfunc (d Decimal) Multiply(other Decimal) DecimalMultiplicación
Dividefunc (d Decimal) Divide(other Decimal) (Decimal, error)División (precisión de 16 dígitos)
Negatefunc (d Decimal) Negate() DecimalNegación
Absfunc (d Decimal) Abs() DecimalValor absoluto
Ceilingfunc (d Decimal) Ceiling() IntegerMenor entero >= d
Floorfunc (d Decimal) Floor() IntegerMayor entero <= d
Truncatefunc (d Decimal) Truncate() IntegerParte entera
Roundfunc (d Decimal) Round(precision int32) DecimalRedondear a precisión
Powerfunc (d Decimal) Power(exp Decimal) DecimalExponenciación
Sqrtfunc (d Decimal) Sqrt() (Decimal, error)Raíz cuadrada
Expfunc (d Decimal) Exp() Decimale^d
Lnfunc (d Decimal) Ln() (Decimal, error)Logaritmo natural
Logfunc (d Decimal) Log(base Decimal) (Decimal, error)Logaritmo con base personalizada
IsIntegerfunc (d Decimal) IsInteger() boolVerdadero si no tiene parte fraccionaria
ToIntegerfunc (d Decimal) ToInteger() (Integer, bool)Convierte a Integer si es número entero
Comparefunc (d Decimal) Compare(other Value) (int, error)Comparación (funciona con Integer y Decimal)

Ejemplo:

pi, _ := types.NewDecimal("3.14159")
two := types.NewDecimalFromInt(2)

fmt.Println(pi.Add(two))           // 5.14159
fmt.Println(pi.Multiply(two))      // 6.28318
fmt.Println(pi.Round(2))           // 3.14
fmt.Println(pi.Ceiling())          // 4
fmt.Println(pi.Floor())            // 3
fmt.Println(pi.IsInteger())        // false

// MustDecimal for constants
half := types.MustDecimal("0.5")
fmt.Println(half)                  // 0.5

String

Representa un valor de cadena FHIRPath.

type String struct {
    // unexported fields
}

Implementa: Value, Comparable

NewString

func NewString(v string) String

Métodos Principales

MétodoFirmaDescripción
Valuefunc (s String) Value() stringRetorna la cadena de Go subyacente
Lengthfunc (s String) Length() intNúmero de caracteres (conteo de runas)
Containsfunc (s String) Contains(substr string) boolVerificación de subcadena
StartsWithfunc (s String) StartsWith(prefix string) boolVerificación de prefijo
EndsWithfunc (s String) EndsWith(suffix string) boolVerificación de sufijo
Upperfunc (s String) Upper() StringMayúsculas
Lowerfunc (s String) Lower() StringMinúsculas
IndexOffunc (s String) IndexOf(substr string) intÍndice de primera aparición (-1 si no se encuentra)
Substringfunc (s String) Substring(start, length int) StringExtraer subcadena
Replacefunc (s String) Replace(old, replacement string) StringReemplazar todas las apariciones
ToCharsfunc (s String) ToChars() CollectionDividir en cadenas de un solo carácter
Comparefunc (s String) Compare(other Value) (int, error)Comparación lexicográfica

Comportamiento de equivalencia: Equivalent() para cadenas es insensible a mayúsculas y normaliza los espacios en blanco (elimina espacios al inicio/final, colapsa espacios internos a espacios simples).

Ejemplo:

s := types.NewString("Hello, World!")

fmt.Println(s.Length())                  // 13
fmt.Println(s.Contains("World"))         // true
fmt.Println(s.StartsWith("Hello"))       // true
fmt.Println(s.Upper())                   // HELLO, WORLD!
fmt.Println(s.Lower())                   // hello, world!
fmt.Println(s.IndexOf("World"))          // 7
fmt.Println(s.Substring(0, 5))           // Hello
fmt.Println(s.Replace("World", "Go"))    // Hello, Go!

// Equivalence is case-insensitive
a := types.NewString("  hello  world  ")
b := types.NewString("Hello World")
fmt.Println(a.Equivalent(b))             // true
fmt.Println(a.Equal(b))                  // false

Date

Representa un valor de fecha FHIRPath con precisión variable (año, año-mes o año-mes-día).

type Date struct {
    // unexported fields
}

Implementa: Value, Comparable

Constructores

FunciónFirmaDescripción
NewDatefunc NewDate(s string) (Date, error)Analiza "2024", "2024-03" o "2024-03-15"
NewDateFromTimefunc NewDateFromTime(t time.Time) DateCrea desde time.Time con precisión de día

Constantes de Precisión

type DatePrecision int

const (
    YearPrecision  DatePrecision = iota // e.g., "2024"
    MonthPrecision                       // e.g., "2024-03"
    DayPrecision                         // e.g., "2024-03-15"
)

Métodos Principales

MétodoFirmaDescripción
Yearfunc (d Date) Year() intComponente de año
Monthfunc (d Date) Month() intComponente de mes (0 si no está especificado)
Dayfunc (d Date) Day() intComponente de día (0 si no está especificado)
Precisionfunc (d Date) Precision() DatePrecisionEl nivel de precisión
ToTimefunc (d Date) ToTime() time.TimeConvierte a time.Time (valores por defecto para componentes faltantes)
AddDurationfunc (d Date) AddDuration(value int, unit string) DateSuma una duración temporal
SubtractDurationfunc (d Date) SubtractDuration(value int, unit string) DateResta una duración temporal
Comparefunc (d Date) Compare(other Value) (int, error)Comparación (puede retornar error para precisión ambigua)

Unidades de duración soportadas para AddDuration/SubtractDuration: "year", "years", "month", "months", "week", "weeks", "day", "days".

Ejemplo:

d, _ := types.NewDate("2024-03-15")
fmt.Println(d.Year())       // 2024
fmt.Println(d.Month())      // 3
fmt.Println(d.Day())        // 15
fmt.Println(d.Precision())  // DayPrecision

// Partial date
partial, _ := types.NewDate("2024-03")
fmt.Println(partial)          // 2024-03
fmt.Println(partial.Day())   // 0 (not specified)

// Date arithmetic
next := d.AddDuration(1, "month")
fmt.Println(next)            // 2024-04-15

DateTime

Representa un valor de fecha y hora FHIRPath con precisión variable desde año hasta milisegundo, con zona horaria opcional.

type DateTime struct {
    // unexported fields
}

Implementa: Value, Comparable

Constructores

FunciónFirmaDescripción
NewDateTimefunc NewDateTime(s string) (DateTime, error)Analiza cadenas datetime ISO 8601
NewDateTimeFromTimefunc NewDateTimeFromTime(t time.Time) DateTimeCrea desde time.Time con precisión de milisegundo

Los formatos aceptados incluyen: "2024", "2024-03", "2024-03-15", "2024-03-15T10:30", "2024-03-15T10:30:00", "2024-03-15T10:30:00.000", "2024-03-15T10:30:00Z", "2024-03-15T10:30:00+05:00".

Constantes de Precisión

type DateTimePrecision int

const (
    DTYearPrecision   DateTimePrecision = iota
    DTMonthPrecision
    DTDayPrecision
    DTHourPrecision
    DTMinutePrecision
    DTSecondPrecision
    DTMillisPrecision
)

Métodos Principales

MétodoFirmaDescripción
Yearfunc (dt DateTime) Year() intComponente de año
Monthfunc (dt DateTime) Month() intComponente de mes
Dayfunc (dt DateTime) Day() intComponente de día
Hourfunc (dt DateTime) Hour() intComponente de hora
Minutefunc (dt DateTime) Minute() intComponente de minuto
Secondfunc (dt DateTime) Second() intComponente de segundo
Millisecondfunc (dt DateTime) Millisecond() intComponente de milisegundo
ToTimefunc (dt DateTime) ToTime() time.TimeConvierte a time.Time
AddDurationfunc (dt DateTime) AddDuration(value int, unit string) DateTimeSuma una duración temporal
SubtractDurationfunc (dt DateTime) SubtractDuration(value int, unit string) DateTimeResta una duración temporal
Comparefunc (dt DateTime) Compare(other Value) (int, error)Comparación (puede retornar error para precisión ambigua)

Unidades de duración soportadas: "year", "years", "month", "months", "week", "weeks", "day", "days", "hour", "hours", "minute", "minutes", "second", "seconds", "millisecond", "milliseconds", "ms".

Ejemplo:

dt, _ := types.NewDateTime("2024-03-15T14:30:00Z")
fmt.Println(dt.Year())        // 2024
fmt.Println(dt.Hour())        // 14
fmt.Println(dt.Minute())      // 30
fmt.Println(dt)               // 2024-03-15T14:30:00Z

// DateTime arithmetic
later := dt.AddDuration(2, "hours")
fmt.Println(later)             // 2024-03-15T16:30:00Z

// From time.Time
now := types.NewDateTimeFromTime(time.Now())
fmt.Println(now.Type())        // DateTime

Time

Representa un valor de hora FHIRPath con precisión variable desde hora hasta milisegundo.

type Time struct {
    // unexported fields
}

Implementa: Value, Comparable

Constructores

FunciónFirmaDescripción
NewTimefunc NewTime(s string) (Time, error)Analiza cadenas de hora como "14:30", "14:30:00", "T14:30:00.000"
NewTimeFromGoTimefunc NewTimeFromGoTime(t time.Time) TimeCrea desde time.Time con precisión de milisegundo

Constantes de Precisión

type TimePrecision int

const (
    HourPrecision   TimePrecision = iota
    MinutePrecision
    SecondPrecision
    MillisPrecision
)

Métodos Principales

MétodoFirmaDescripción
Hourfunc (t Time) Hour() intComponente de hora
Minutefunc (t Time) Minute() intComponente de minuto
Secondfunc (t Time) Second() intComponente de segundo
Millisecondfunc (t Time) Millisecond() intComponente de milisegundo
Comparefunc (t Time) Compare(other Value) (int, error)Comparación (puede retornar error para precisión ambigua)

Ejemplo:

t, _ := types.NewTime("14:30:00")
fmt.Println(t.Hour())        // 14
fmt.Println(t.Minute())      // 30
fmt.Println(t.Second())      // 0
fmt.Println(t)               // 14:30:00

// With milliseconds
precise, _ := types.NewTime("T08:15:30.500")
fmt.Println(precise.Millisecond()) // 500

Quantity

Representa una cantidad FHIRPath – un valor numérico combinado con una cadena de unidad. Soporta normalización de unidades UCUM para comparar cantidades con unidades diferentes pero compatibles.

type Quantity struct {
    // unexported fields
}

Implementa: Value, Comparable

Constructores

FunciónFirmaDescripción
NewQuantityfunc NewQuantity(s string) (Quantity, error)Analiza cadenas como "5.5 'mg'", "100 kg"
NewQuantityFromDecimalfunc NewQuantityFromDecimal(value decimal.Decimal, unit string) QuantityCrea desde un decimal.Decimal y cadena de unidad

Métodos Principales

MétodoFirmaDescripción
Valuefunc (q Quantity) Value() decimal.DecimalRetorna el valor numérico
Unitfunc (q Quantity) Unit() stringRetorna la cadena de unidad
Addfunc (q Quantity) Add(other Quantity) (Quantity, error)Suma (misma unidad requerida)
Subtractfunc (q Quantity) Subtract(other Quantity) (Quantity, error)Resta (misma unidad requerida)
Multiplyfunc (q Quantity) Multiply(factor decimal.Decimal) QuantityMultiplicar por un número
Dividefunc (q Quantity) Divide(divisor decimal.Decimal) (Quantity, error)Dividir por un número
Normalizefunc (q Quantity) Normalize() ucum.NormalizedQuantityNormalización UCUM
Comparefunc (q Quantity) Compare(other Value) (int, error)Comparación (soporta unidades compatibles vía UCUM)

Comportamiento de equivalencia: Equivalent() para cantidades utiliza normalización UCUM, por lo que 10 'cm' y 0.1 'm' se consideran equivalentes.

Ejemplo:

q, _ := types.NewQuantity("75.5 'kg'")
fmt.Println(q.Value()) // 75.5
fmt.Println(q.Unit())  // kg
fmt.Println(q)         // 75.5 kg

// Arithmetic
q2, _ := types.NewQuantity("2.5 'kg'")
sum, _ := q.Add(q2)
fmt.Println(sum)       // 78 kg

ObjectValue

Representa un recurso FHIR® o tipo complejo como un objeto JSON. Este tipo se utiliza internamente para representar datos estructurados dentro del motor de evaluación. El método Type() intenta inferir el tipo FHIR® desde la estructura JSON (verificando resourceType primero, luego patrones estructurales para tipos complejos comunes).

type ObjectValue struct {
    // unexported fields
}

Implementa: Value

NewObjectValue

func NewObjectValue(data []byte) *ObjectValue

Crea un ObjectValue desde bytes JSON crudos que representan un objeto.

Métodos Principales

MétodoFirmaDescripción
Typefunc (o *ObjectValue) Type() stringTipo FHIR® inferido u "Object"
Datafunc (o *ObjectValue) Data() []byteBytes JSON crudos
Getfunc (o *ObjectValue) Get(field string) (Value, bool)Obtener un valor de campo (con caché)
GetCollectionfunc (o *ObjectValue) GetCollection(field string) CollectionObtener un campo como Collection
Keysfunc (o *ObjectValue) Keys() []stringTodos los nombres de campo
Childrenfunc (o *ObjectValue) Children() CollectionTodos los valores hijos
ToQuantityfunc (o *ObjectValue) ToQuantity() (Quantity, bool)Convertir a Quantity si la estructura coincide

Inferencia de tipo: El método Type() reconoce tipos de recurso FHIR® (vía el campo resourceType) y tipos complejos comunes incluyendo Quantity, Coding, CodeableConcept, Reference, Period, Identifier, Range, Ratio, Attachment, HumanName, Address, ContactPoint y Annotation.

Ejemplo:

data := []byte(`{"resourceType": "Patient", "id": "123", "active": true}`)
obj := types.NewObjectValue(data)

fmt.Println(obj.Type()) // Patient

if v, ok := obj.Get("id"); ok {
    fmt.Println(v) // 123
}

keys := obj.Keys()
fmt.Println(keys) // [resourceType id active]

TypeError

Representa un error de incompatibilidad de tipos que puede ocurrir durante operaciones con valores.

type TypeError struct {
    Expected  string
    Actual    string
    Operation string
}

NewTypeError

func NewTypeError(expected, actual, operation string) *TypeError

Error

func (e *TypeError) Error() string
// Returns: "type error in <operation>: expected <expected>, got <actual>"

Ejemplo:

err := types.NewTypeError("Integer", "String", "comparison")
fmt.Println(err.Error()) // type error in comparison: expected Integer, got String

Funciones de Utilidad

JSONToCollection

Convierte bytes JSON crudos (que pueden ser un objeto, arreglo o primitivo) a una Collection.

func JSONToCollection(data []byte) (Collection, error)

Comportamiento:

  • Objeto JSON: Retorna una colección singleton con un *ObjectValue
  • Arreglo JSON: Retorna una colección con un elemento por cada ítem del arreglo
  • JSON null: Retorna una colección vacía
  • Primitivo JSON: Retorna una colección singleton con el tipo correspondiente

Resumen de Tipos

TipoNombre FHIRPathTipo Go SubyacenteImplementa
BooleanBooleanboolValue
IntegerIntegerint64Value, Comparable, Numeric
DecimalDecimaldecimal.DecimalValue, Comparable, Numeric
StringStringstringValue, Comparable
DateDateyear/month/day intsValue, Comparable
DateTimeDateTimecomponent ints + timezoneValue, Comparable
TimeTimehour/minute/second/millis intsValue, Comparable
QuantityQuantitydecimal.Decimal + unit stringValue, Comparable
*ObjectValue(inferred)[]byte JSONValue
Última actualización