Haskell记录模式匹配 [英] Haskell record pattern matching

查看:149
本文介绍了Haskell记录模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  data X = A我想要一种简化函数模式的方法| B字符串| C Int Int字符串
myfn :: X - > Int
myfn A = 50
myfn(B _)= 200
myfn(C _ _ _)= 500

有没有办法让匹配C的模式更简单,只是丢弃这些值?



hsdev增加了一个提示提示:使用记录模式,但谷歌没有帮助我。

解决方案

您可以使用像这样的记录模式: p>

  data X = A | B {name :: String} | C {x :: Int,y :: Int,name :: String} 

myfn :: X - > Int
myfn A = 50
myfn B {} = 200
myfn C {} = 500

记录模式允许您为构造函数的字段提供名称。
你也可以这样做:

  myfn C {name = n} = length n 

所以你可以看到你只能在你需要的特定领域进行模式匹配。



注意:即使对于不使用记录语法的数据类型,也可以使用记录模式:

  data A = A Int | B Int Int 

myfn A {} = 1
myfn B {} = 2

这很好。
其他一些与记录模式相关的扩展:


  • RecordWildCards 允许你写下类似于 C {..} 的东西,它等价于下面的模式: C {x = x,y = y ,name = name} ,即它匹配所有字段,现在你的范围 x 的值与 x 字段等。

  • NamedFieldPuns 允许您写 C {name} 相当于 C {name = name} ,所以 name 现在处于范围内,并包含与名称字段匹配的值。




请记住,使用记录模式并不妨碍您以定位方式使用构造函数,因此您仍然可以编写:

  myfn(B _)= 200 

增加了功能。


I'm looking for a way to simplify function patterns when the actual data is not required:

data X = A | B String | C Int Int String
myfn :: X -> Int
myfn A = 50
myfn (B _) = 200
myfn (C _ _ _) = 500

Is there a way to make a simpler pattern for matching C, just discarding the values?

hsdev adds a hint "Hint: use record patterns", but Google did not help me there.

解决方案

You can use record patterns like this:

data X = A | B {name :: String} | C {x::Int, y::Int, name::String}

myfn :: X -> Int
myfn A = 50
myfn B{} = 200
myfn C{} = 500

Record patterns allow you to give names to the fields of the constructors. you can also do things like:

myfn C{name=n} = length n

so you can see that you can pattern match only on the specific field you need.

Note: you can use the empty record pattern even with data types that do not use record syntax:

data A = A Int | B Int Int

myfn A{} = 1
myfn B{} = 2

This is fine. There a number of other extensions related to record patterns:

  • RecordWildCards allows you to write things like C{..} which is equivalent to the pattern: C{x=x, y=y, name=name}, i.e. it matches all fields and you now have in scope x with the value matched for the x field etc.

  • NamedFieldPuns allows you to write C{name} to be equivalent to C{name=name}, so that name is now in scope and contains the value matched for the name field.

Keep in mind that using record patterns doesn't prevent you from using your constructors in a positional way, so you can still write:

myfn (B _) = 200

It only adds functionality.

这篇关于Haskell记录模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆