guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Safe pattern matching


From: Daniel Hartwig
Subject: Re: Safe pattern matching
Date: Sat, 9 Feb 2013 18:12:59 +0800

On 9 February 2013 17:57, Nikita Karetnikov <address@hidden> wrote:
> Any Haskellers here?
>
> How would you rewrite the following function in Guile?
>
> foo :: [Int] -> String -> [Int]
> foo (x:y:ys) "+" = (x + y):ys
> foo (x:y:ys) "-" = (x - y):ys
> foo xs       num = read num:xs

Indeed, match can do this.  The style is very similar.

Using symbols and literals, rather than strings:

> (use-modules (ice-9 match))
> (define (foo . args)
    (match args
      (((x y . ys) '+)
       (cons (+ x y) ys))
      (((x y . ys) '-)
       (cons (- x y) ys))
      ((xs num)
       (cons num xs))))
> (foo '() 42)
$1 = (42)
> (foo '(1 2) 42)
$2 = (42 1 2)
> (foo '(1 2) '+)
$3 = (3)
> (use-modules (srfi srfi-1))
> (foo (iota 10 1) 42)
$4 = (42 1 2 3 4 5 6 7 8 9 10)
> (foo (iota 10 1) '+)
$5 = (3 3 4 5 6 7 8 9 10)



reply via email to

[Prev in Thread] Current Thread [Next in Thread]