我写了一个程序,结果发现使用列表太慢了,所以我试图切换到序列。但是,在查看文档之后,我似乎无法弄清楚正确的语法。
到目前为止,我尝试使用这个简单的代码学习:
import Control.Monad
import qualified Data.Sequence as S
main :: IO ()
main = do
let testSeq = S.empty
testSeq S.|> 5
testSeq S.|> 20
testSeq S.|> 3
let newSeq = S.update 2 3 testSeq
let x = lookup 2 testSeq
print x
我已经玩了一段时间没有运气的语法,但它仍然有很多错误:
test.hs:9:8:
Couldn't match expected type ‘IO a0’
with actual type ‘S.Seq Integer’
In a stmt of a 'do' block: testSeq S.|> 5
In the expression:
do { let testSeq = S.empty;
testSeq S.|> 5;
testSeq S.|> 20;
testSeq S.|> 3;
.... }
In an equation for ‘main’:
main
= do { let testSeq = ...;
testSeq S.|> 5;
testSeq S.|> 20;
.... }
test.hs:10:8:
Couldn't match expected type ‘IO a1’
with actual type ‘S.Seq Integer’
In a stmt of a 'do' block: testSeq S.|> 20
In the expression:
do { let testSeq = S.empty;
testSeq S.|> 5;
testSeq S.|> 20;
testSeq S.|> 3;
.... }
In an equation for ‘main’:
main
= do { let testSeq = ...;
testSeq S.|> 5;
testSeq S.|> 20;
.... }
test.hs:11:8:
Couldn't match expected type ‘IO a2’
with actual type ‘S.Seq Integer’
In a stmt of a 'do' block: testSeq S.|> 3
In the expression:
do { let testSeq = S.empty;
testSeq S.|> 5;
testSeq S.|> 20;
testSeq S.|> 3;
.... }
In an equation for ‘main’:
main
= do { let testSeq = ...;
testSeq S.|> 5;
testSeq S.|> 20;
.... }
test.hs:13:25:
Couldn't match expected type ‘[(Integer, b)]’
with actual type ‘S.Seq a3’
Relevant bindings include x :: Maybe b (bound at test.hs:13:12)
In the second argument of ‘lookup’, namely ‘testSeq’
In the expression: lookup 2 testSeq
我是Haskell的新手,所以非常感谢任何帮助!
答案 0 :(得分:4)
与Haskell中的几乎所有内容一样,Seq
是一个纯粹的功能数据结构。它不像是一个必要的堆栈,你可以推送东西,改变原始结构。相反,与普通列表一样,您只需生成具有额外元素的新容器值,但这不会以任何方式影响旧的较短seq。所以,你问过的程序应该只是
testSeq :: S.Seq Int
testSeq = S.update 2 3 $ S.empty S.|> 5 S.|> 20 S.|> 30
main :: IO ()
main = print $ S.lookup 2 testSeq
(必须是S.lookup
,或等效S.!?
。lookup
本身就是一个适用于普通列表的函数!)
请注意,这并没有真正优于
testSeq = S.update 2 3 $ S.fromList [5,20,30]
事实上,列表通常比<{em}更快,它们只是不允许有效的随机访问。