每個人!我一直在通過這個系列講座學習 Haskell ,我正在嘗試完成第 1 課的練習(鏈接在視頻的描述中)。我在以下練習中遇到問題:
{- | Implement a function that takes a string, start and end positions
and returns a substring of a given string from the start position to
the end (including).
>>> subString 3 7 "Hello, world!"
"lo, w"
>>> subString 10 5 "Some very long String"
""
This function can accept negative start and end position. Negative
start position can be considered as zero (e.g. substring from the
first character) and negative end position should result in an empty
string.
-}
subString start end str = error "TODO"
我嘗試的實作是這樣的:
subString :: Int -> Int -> [a] -> [a]
subString start end str
| end < 0 = []
| start < 0 = subString 0 end str
| otherwise = take ((end - start) 1) (drop start str)
這給出了函式之前注釋中包含的測驗的預期結果(subString 3 7 "Hello, world!"適當地給出"lo, w"和subString 10 5 "Some very long String"適當地給出"")。但是評論還說它應該適用于 start 和 end 的負值,這就是為什么我包括警衛來指定負數的預期行為。但是,當我在 ghci 中加載模塊并呼叫subString -1 4 "Hello, world"時,出現此錯誤:
<interactive>:25:1: error:
? Non type-variable argument
in the constraint: Num (t -> [Char] -> Int -> Int -> [a] -> [a])
(Use FlexibleContexts to permit this)
? When checking the inferred type
it :: forall t a.
(Num t, Num (t -> [Char] -> Int -> Int -> [a] -> [a]),
Num (Int -> Int -> [a] -> [a])) =>
Int -> Int -> [a] -> [a]
在大多數情況下,我發現 Haskell 錯誤訊息比我學過/嘗試過的其他語言更有幫助,但這條訊息對我來說完全是一派胡言。這里發生了什么?
(注意:在我學習 Haskell 的這個階段,我不在乎我撰寫這個函式的方式是否單一。我只是想讓它按預期作業。)
uj5u.com熱心網友回復:
否定文字通常需要用括號括起來:
subString (-1) 4 "Hello, world"
否則將-被決議為中綴減法運算子:
(subString) - (1 4 "Hello, world")
...很少進行型別檢查,甚至更沒有意義。作為推論,如果你想要一個省略第一個引數的運算子部分-,你不能使用語法(-1); 取而代之的是使用subtract 1(如果需要的話,可以用括號括起來)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/477443.html
標籤:哈斯克尔
上一篇:具有Bang模式的HaskellStrictMVar
下一篇:模板Haskell決議型別別名
