3

Haskell: Prefer matching patterns or member access?

 2 years ago
source link: https://www.codesd.com/item/haskell-prefer-matching-patterns-or-member-access.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Haskell: Prefer matching patterns or member access?

advertisements

Suppose I have a Vector datatype defined as follows:

data Vector = Vector { x :: Double
                     , y :: Double
                     , z :: Double
                     }

Would it be more usual to define functions against it using member access:

vecAddA v w
    = Vector (x v + x w)
             (y v + y w)
             (z v + z w)

Or using pattern-matching:

vecAddB (Vector vx vy vz) (Vector wx wy wz)
    = Vector (vx + wx)
             (vy + wy)
             (vz + wz)

(Apologies if I've got any of the terminology incorrect).


I would normally use pattern matching, especially since you're using all of the constructor's arguments and there aren't a lot of them. Also, In this example it's not an issue, but consider the following:

data Foo = A {a :: Int} | B {b :: String}

fun x = a x + 1

If you use pattern matching to do work on the Foo type, you're safe; it's not possible to access a member that doesn't exist. If you use accessor functions on the other hand, some operations such as calling fun (B "hi!") here will result in a runtime error.

EDIT: while it's of course quite possible to forget to match on some constructor, pattern matching makes it pretty explicit that what happens depends on what constructor is used (you can also tell the compiler to detect and warn you about incomplete patterns) whereas the use of a function hints more that any constructor goes, IMO.

Accessors are best saved for cases when you want to get at just one or a few of the constructor's (potentially many) arguments and you know that it's safe to use them (no risk of using an accessor on the wrong constructor, as in the example.)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK