在 SML/NJ 中使用列表/模式匹配
我在与 SML 中的列表进行模式匹配时遇到问题。我正在尝试创建一个函数,该函数采用 2x2 实数矩阵(定义为 'a list list
)并创建复杂的 (real * real)
。该矩阵被格式化为列表列表(由实数组成),每个列表都是一行。我知道我必须进行模式匹配,但我不确定如何将我的理解应用到实际代码中。到目前为止我的代码是:
fun fromMatrix ((a::M):real matrix) : complex = (hd a, tl M);
我不断收到此错误:
stdIn:1.5-13.32 Error: right-hand-side of clause doesn't agree with function result type [tycon mismatch]
expression: real * real list list
result type: complex
in declaration:
fromMatrix =
(fn <pat> :: <pat> : real matrix => (hd <exp>,tl <exp>): complex)
I'm having trouble with pattern matching with lists in SML. I'm trying to create a function that takes a 2x2 real matrix (defined as 'a list list
) and creates a complex (real * real)
. The matrix is formatted as a list of lists(that are made with reals) with each list being a row. I know that I have to pattern match but I'm unsure how to implement my understanding into actual code. My code thus far is:
fun fromMatrix ((a::M):real matrix) : complex = (hd a, tl M);
I keep getting this error:
stdIn:1.5-13.32 Error: right-hand-side of clause doesn't agree with function result type [tycon mismatch]
expression: real * real list list
result type: complex
in declaration:
fromMatrix =
(fn <pat> :: <pat> : real matrix => (hd <exp>,tl <exp>): complex)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,如果
(a::M)
具有类型real matrix
(或real list list
),那么这意味着a(head)的类型为
real list
,M
(tail)的类型为real list list
。那么hd a
的类型为real
,tl M
的类型为real list list
。因此,将它们放在一起,(hd a, tl M)
的类型为real * real list list
,可能不是您想要的。您可能想了解,对于列表,
x :: y
表示x
是第一个元素,y
是列表的其余元素(不是第二个元素),这是一个列表。类似地,hd
函数返回列表的第一个元素,tl
函数返回列表的其余部分。如果要提取前两个元素,可以使用模式x :: y :: z
(其中z
是前 2 个元素之后的列表的其余部分) )。如果您知道它将是一个 2 元素列表,则可以匹配x :: y :: []
,或者等效地,[x, y]
。您可以嵌套模式,因此如果您有一个 2 元素列表的 2 元素列表,则可以直接匹配[[a, b], [c, d]]
。然而,使用固定大小的列表是糟糕设计的标志。您可能想改用元组。Okay so if
(a::M)
has typereal matrix
(orreal list list
), then that meansa
(head) has typereal list
andM
(tail) has typereal list list
. Thenhd a
has typereal
, andtl M
has typereal list list
. So putting them together,(hd a, tl M)
has typereal * real list list
, probably not what you want.You probably want to understand that for lists,
x :: y
means thatx
is the first element, andy
is the rest of the list (not the second element), which is a list. Similarly, thehd
function returns the first element of a list, and thetl
function returns the rest of the list. If you want to extract the first two elements, you could use the patternx :: y :: z
(wherez
is the rest of the list after the first 2 elements). If you know it's going to be a 2-element list, you could matchx :: y :: []
, or equivalently,[x, y]
. You can nest patterns, so if you have a 2-element list of 2-element lists, you could directly match[[a, b], [c, d]]
. However, using a fixed-size list is a sign of bad design. You probably want to use a tuple instead.