Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern match in function argument in haskell

Tags:

haskell

In the code defining a function, there is a strange "pattern match" (cradleRootDir -> projdir)

I guess that is meant to apply the function inline and binds the result to the name projdir.

What is the name of that construct ?

withGhcModEnv' :: (IOish m, GmOut m) => (FilePath -> (Cradle -> m a) -> m a) -> FilePath -> Options -> ((GhcModEnv, GhcModLog) -> m a) -> m a
withGhcModEnv' withCradle dir opts f =
    withCradle dir $ \crdl ->
      withCradleRootDir crdl $
        f (GhcModEnv opts crdl, undefined)
 where
   withCradleRootDir (cradleRootDir -> projdir) a = do
       cdir <- liftIO $ getCurrentDirectory
       eq <- liftIO $ pathsEqual projdir cdir
       if not eq
          then throw $ GMEWrongWorkingDirectory projdir cdir
          else a

The constructor

data Cradle = Cradle {
    cradleCurrentDir :: FilePath
  , cradleRootDir    :: FilePath
  , cradleCabalFile  :: Maybe FilePath
  , cradlePkgDbStack  :: [GhcPkgDb]
  } deriving (Eq, Show)
like image 535
nicolas Avatar asked Oct 27 '15 11:10

nicolas


People also ask

How do I use pattern matching in Haskell?

You do that by putting a name and an @ in front of a pattern. For instance, the pattern xs@(x:y:ys). This pattern will match exactly the same thing as x:y:ys but you can easily get the whole list via xs instead of repeating yourself by typing out x:y:ys in the function body again.

Does Haskell have pattern matching?

We use pattern matching in Haskell to simplify our codes by identifying specific types of expression. We can also use if-else as an alternative to pattern matching. Pattern matching can also be seen as a kind of dynamic polymorphism where, based on the parameter list, different methods can be executed.

Why ++ is not allowed in pattern matching?

You can only pattern-match on data constructors, and ++ is a function, not a data constructor. Data constructors are persistent; a value like 'c':[] cannot be simplified further, because it is a fundamental value of type [Char] .

What is pattern matching explain with example?

Pattern matching is the process of checking whether a specific sequence of characters/tokens/data exists among the given data. Regular programming languages make use of regular expressions (regex) for pattern matching.


1 Answers

It's using View Patterns

Evaluation To match a value v against a pattern (expr -> pat), evaluate (expr v) and match the result against pat.

See cabal file

Default-Extensions:   ScopedTypeVariables, RecordWildCards, NamedFieldPuns,
                      ConstraintKinds, FlexibleContexts,
                      DataKinds, KindSignatures, TypeOperators, ViewPatterns
                                                                ^^^^^^^^^^^^
                                                                |  |  |  | |
like image 184
josejuan Avatar answered Nov 13 '22 15:11

josejuan