首页 > 解决方案 > 对由一个列表组成的自身类型的列表操作

问题描述

我得到了类型“ Signal”,它只是一个双打列表,我想使用普通的列表操作,比如在 native [Double]. 这应该是可能的,但它不会编译。您将如何在语法上正确地向编译器描述这一点。

这是测试代码:

data Signal = Signal [Double] deriving(Show, Eq)

test :: Signal
test = Signal [1.0,2.0,3.0]

take2 :: Signal -> Signal
take2 s = take 2 s

预期的:take2 test = [1.0,2.0]

实际的:

"Couldn't match expected type ‘Signal’ with actual type ‘[a0]’
In the expression: take 2 s
In an equation for ‘take2’: take2 s = take 2 s"

标签: haskellghci

解决方案


注意函数定义如下:

take2 :: Signal -> Signal
take2 s = take 2 s

s不是列表,它是 aSignal并且take 2 s是列表,而不是 a Signal,您需要的是从列表中获取列表并从列表中Signal构造 aSignal为:

take2 (Signal s) = Signal $ take 2 s

推荐阅读