Home > f# > How to use pattern matching within curried function

How to use pattern matching within curried function

September 11Hits:1
Advertisement

I'm learning F# and I'm trying the following exercise (exercise 4.10 of Functional Programming Using F#).

Declare an F# function prefix: 'a list -> 'a list -> bool when a:equality. The value of the expression prefix[x_0;x_1;...;x_m] [y_0;y_1;...;y_n] is true if m<=n and x_i=y_i for 0<=i<=m, and false otherwise.

I wanted to use pattern matching on the two inputs, but wasn't sure how to do this with a curried function (as opposed to a function taking a 2-tuple). So I wrote:

let rec prefix a b = (function     | ([], _) -> true     | (_, []) -> false     | (x0::xst,y0::yst) -> x0 = y0 && prefix xst yst) (a,b);; 

I wasn't very happy with this, because I thought it would be better (clearer and more efficient) if the inner function called itself, so I tried declaring the inner function locally.

let prefix a b =     let rec prefixt = function         | ([], _) -> true         | (_, []) -> false         | (x0::xst,y0::yst) -> x0 = y0 && prefixt (xst,yst)     prefixt (a,b);; 

Is this the right way to approach such a problem in F#?

Answers

You can use the match … with … syntax:

let rec prefix a b =
    match (a, b) with
    | ([], _) -> true
    | (_, []) -> false
    | (x0::xst,y0::yst) -> x0 = y0 && prefix xst yst

Tags:

Related Articles

  • How to use pattern matching within curried functionSeptember 11

    I'm learning F# and I'm trying the following exercise (exercise 4.10 of Functional Programming Using F#). Declare an F# function prefix: 'a list -> 'a list -> bool when a:equality. The value of the expression prefix[x_0;x_1;...;x_m] [y_0;y_1;...;y_n

  • Pattern matching on Orderless functions inside HoldAugust 9

    MatchQ[Hold[1 + 2], Hold[2 + 1]] returns False. But in the presence of a Blank[] in the matching pattern as in the example below MatchQ[Hold[1 + 2], Hold[2 + _]] which returns True, apparently the fact that Plus is Orderless is being respected. Apart

  • Custom operators; custom pattern matching with pure functionsMay 30

    What I'm trying to achieve in Mathematica is the creation of a binary operator whose operands are both pure functions over the natural numbers. The result of the operator should be another pure function over the natural numbers. To demonstrate concre

  • Why is pattern matching preferred in function definitions?February 5

    I am reading the "learnyouahaskell" tutorial from learnyouahaskell. There it reads: Pattern matching can also be used on tuples. What if we wanted to make a function that takes two vectors in a 2D space (that are in the form of pairs) and adds t

  • Placement of pattern matching rules in functions

    Placement of pattern matching rules in functions January 23

    It is my practice to place Condition expressions on the left side of := and :> in almost every case. I find this to be more logical as it is part of the pattern With the exception of use inside Module, Block, or With on the RHS, which is a special ca

  • How to Enable Syntax Coloring of Pattern Match Variable Only (i.e. Without Coloring any Associated Pattern)?

    How to Enable Syntax Coloring of Pattern Match Variable Only (i.e. Without Coloring any Associated Pattern)?May 1

    Syntax coloring for the following function definition foo[x_List] := ... will color green (and italicize by default) the argument name x as well as the pattern name _List: On the other hand, syntax coloring for foo[x:_List] colors only the identifier

  • Is pattern-matching against types idiomatic or poor design?March 3

    It seems like F# code often pattern matches against types. Certainly match opt with | Some val -> Something(val) | None -> Different() seems common. But from an OOP perspective, that looks an awful lot like control-flow based on a runtime type check

  • Haskell: Using patten matching with currying dataJanuary 22

    Is it possible to use patten matching with a currying data? Suppose the following code: data Bind = Echo String | Sum Int Int getOperation (Echo x ) = "Echo" getOperation (Sum x y ) = "Sum" main = getOperation (Sum 1) It fails because

  • Pattern-matching functionMay 2

    I am new to Scala and I have written a function which uses pattern matching to filter words based on some conditions. It seems to work correctly but I am suspect that I haven't used the Scala pattern matching in the best way. I think this because eac

  • Pattern matching functions of variablesDecember 1

    I am trying work with a general operator z[] and later plug in candidate forms for z[]. But pattern matching turns the inside z[] into a constant and can no longer perform operations on it: r = z[(x + 2)^2]; r /. z[a_] -> Expand[a] r /. z[a_] -> Int

  • Replacement of terms/Pattern matching involving products of derivatives of a functionJanuary 23

    In delving into Ramanujan summation, I'm trying to get a hold of the relations of the form $$\sum_{n=0}^\infty f(n)=\dfrac{h\frac{d}{dx}}{{\mathrm{e}^{h\frac{d}{dx}}}-1}\int_{0}^\infty f(x)\,{\mathrm{d}x}.$$ To express the right hand side in Mathemat

  • Can we say that "all functions in Mathematica are some kind of pattern-matching-and-replacement procedures"? April 17

    This question already has an answer here: Is everything in Mathematica ultimately stored as a rule? 1 answer Currently I am studying Mathematica programming, and when I study pattern matching and replacement, I find it is quite similar to functions.

  • Functional pattern matching in C#September 30

    I recently read a really interesting post on adding functional pattern matching to C#. Here's a quick and dirty implementation using delegates and dictionaries. Right now, I require that Match return an object of type TReturn. Is there any way I can

  • How to use pattern matching to apply a function to specific elements of a matrix

    How to use pattern matching to apply a function to specific elements of a matrixOctober 21

    I have a 3x3 matrix testweightedgraph = {{{}, {p, q, pq, pq}, {}}, {{p, q, pq, pq}, {q}, {}}, {{}, {}, {}}}; whose elements are (possibly empty) lists. I would like to apply the pure function 1 - Apply[Times, 1 - #] & to every nonempty element of the

  • Using regex pattern match in xhprof ignore function

    Using regex pattern match in xhprof ignore functionJanuary 25

    I am trying to profile a codeigniter application with xhprof. everything is ok. I am getting the report like following... now I am trying to ignore some function during xhprof report generation. For that what I did is like following.... $ignore = arr

  • Pattern Matching Function Call in Scala February 4

    I am a newbie in Scala and functional programming. I want to call a function several times, with combination of parameters based on two variables. Basically, What I am doing right now is this: def someFunction(a: Int, b: Int): Future[Int] = ??? val v

  • Multiline pattern match using sed, awk or grepMarch 28

    Is it possible to do a multiline pattern match using sed, awk or grep? Take for example, I would like to get all the lines between { and } So it should be able to match 1. {} 2. {.....} 3. {..... .....} Initially the question used <p> as an example.

  • Pattern matching with LIKE, SIMILAR TO or regular expressions in PostgreSQLJanuary 15

    I had to write a simple query where I go looking for people's name that start with a B or a D : SELECT s.name FROM spelers s WHERE s.name LIKE 'B%' OR s.name LIKE 'D%' ORDER BY 1 I was wondering if there is a way to rewrite this to become more perfor

  • Using a PatternTest versus a Condition for pattern matchingFebruary 16

    My last question to the site resulted in several answers that involve using pattern matching in Mathematica, a feature I wasn't very familiar with at the time. I am currently reading Mathematica Navigator and am picking up a bit on patterns. Very pow

  • How to set up new types for pattern matching strings?March 6

    Consider the following toy example: I have a set of language sounds, which I partition into two exclusive subsets, consonants and vowels. I want to set up string patterns for e.g. StringMatchQ that may contain restrictions based on the sound specific

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.666 s.