Code Monkey home page Code Monkey logo

go-pattern-match's Introduction

Go pattern matching

Mentioned in Awesome Go Go Report Card build codecov GoDoc LICENSE

It's just another implementation of pattern matching in Go. I have been inspired by Python pattern matching, that's why I wanted to try writing something similar in Go :) For now the following matching are implemented :

  • Simple types (like int, int64, float, float64, bool..).
  • Struct type.
  • Slices (with HEAD, TAIL, OneOf patterns).
  • Dictionary (with ANY, OneOf pattern).
  • Regexp.
  • Additional custom matching (ability to add special matching for some, structs for example).

Usages

Fibonacci example:

func fib(n int) int {
	_, res := match.Match(n).
		When(1, 1).
		When(2, 1).
		When(match.ANY, func() int { return fib(n-1) + fib(n-2) }).
		Result()

	return res.(int)
}

Simple types:

isMatched, mr := match.Match(42).
                When(42, 10).
                Result()
// isMatched - true, mr - 10

With Structs:

  • Simple check value by type
val := TestStruct{1}

isMatched, _ := Match(val).
    When(func(TestStruct) {},  1).
    Result()
  • Check value by type and condition
val := TestStruct{1}

isMatched, _ := Match(val).
	When(func(ts TestStruct) bool { return ts.value == 42 }, 1).
	When(func(ts AnotherStruct) bool { return ts.stringValue == "hello" }, 2).
	Result()

With Maps:

isMatched, mr := match.Match(map[string]int{
                	"rsc": 3711,
                	"r":   2138,
                	"gri": 1908,
                	"adg": 912,
                }).
        	    When(map[string]interface{}{
                	"rsc": 3711,
                	"r":   2138,
                	"gri": 1908,
                	"adg": match.ANY,
            	}, true).
            	Result()

With Slices:

isMatched, mr := match.Match([]int{1, 2, 3, 4, 5, 6}).
            	When([]interface{}{match.HEAD, 3, match.OneOf(3, 4), 5, 6}, 125).
            	Result()

With regexps:

isMatched, mr := match.Match("gophergopher").
            	When("gophergopher", func() interface{} { return true }).
            	Result()

Without result:

func main() {
	Match(val).
	When(42, func() { fmt.Println("You found the answer to life, universe and everything!") }).
	When(ANY, func() { fmt.Println("No.. It's not an answer.") }).
	Result()
}

Installation

Just go get this repository in the following way:

go get github.com/alexpantyukhin/go-pattern-match

Full example

package main

import (
    "fmt"
    "github.com/alexpantyukhin/go-pattern-match"
)

func main() {
    isMatched, mr := match.Match([]int{1, 2, 3}).
        When(42, false).
        When([]interface{}{match.HEAD, 2, 3}, true).
        Result()


    if isMatched {
        fmt.Println(mr)
    }
}

go-pattern-match's People

Contributors

alekseiaq avatar alexpantyukhin avatar johnlunney avatar panquesito7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

go-pattern-match's Issues

Unable to match `OneOf` with `slice`

Hi!

Using OneOf with slice does not work:

func TestMatch(t *testing.T) {
	isMatched, _ := Match([]string{"one", "two", "three"}).
		When(OneOf([]string{"one", "two", "three"}), true).
		Result()

	assert.True(t, isMatched)
}

Do you have any idea on what is the fix for this? My task involve matching a slice of string with some pattern groups, in which Match is a perfect match. For a workaround, I can try writing a wrapper like:

func OneOfWrapper(items ...interface{}) boolean {
	isMatched, _ := ...
	return isMatched || OneOfWrapper(items[1:]...)
}

But it is not a preferable way, I suppose.

Thanks for the awesome library!

Use generics.

Should we support generics? investigate/implement.

Syntax Error: Unexpected newline in match.go:183:85

Hey! Loving this library, I come from the Elixir/Elm world and wanted to give Go a try but missed my pattern matching.

Getting a strange error when trying to compile an example from the README.

$ belm go run belm.go
# github.com/alexpantyukhin/go-pattern-match
../../go/pkg/mod/github.com/alexpantyukhin/[email protected]/match.go:183:85: syntax error: unexpected newline, expecting { after if clause

Go version

go version go1.19.1 darwin/amd64

The opening brace is there, just on a newline. I managed to fix it by moving the opening brace to the same line of the if statement. So not sure if this a problem with the version of Go I'm using? But it seems very odd there would be a change to the compiler that wouldn't allow a newline after an if statement.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.