我想用Agda中的自然數解析一個字符串。 例如,stringListToℕ "1,2,3"
的結果應該是Just (1 ∷ 2 ∷ 3 ∷ [])
Agda:用數字解析一個字符串
我目前的代碼不是很好,或者任何方式都不錯,但它可以工作。 但是它返回類型: Maybe (List (Maybe ℕ))
的問題是:
如何實現在一個不錯的方式功能
stringListToℕ
(相對於我的代碼); 它應該有類型Maybe (List ℕ)
(可選,並不重要)我怎麼能
Maybe (List (Maybe ℕ))
的類型轉換爲Maybe (List ℕ)
?
我的代碼:
charToℕ : Char → Maybe ℕ
charToℕ '0' = just 0
charToℕ '1' = just 1
charToℕ '2' = just 2
charToℕ '3' = just 3
charToℕ '4' = just 4
charToℕ '5' = just 5
charToℕ '6' = just 6
charToℕ '7' = just 7
charToℕ '8' = just 8
charToℕ '9' = just 9
charToℕ _ = nothing
stringToℕ' : List Char → (acc : ℕ) → Maybe ℕ
stringToℕ' [] acc = just acc
stringToℕ' (x ∷ xs) acc = charToℕ x >>= λ n → stringToℕ' xs (10 * acc + n)
stringToℕ : String → Maybe ℕ
stringToℕ s = stringToℕ' (toList s) 0
isComma : Char → Bool
isComma h = h Ch.== ','
notComma : Char → Bool
notComma ',' = false
notComma _ = true
{-# NO_TERMINATION_CHECK #-}
split : List Char → List (List Char)
split [] = []
split s = l ∷ split (drop (length(l) + 1) s)
where l : List Char
l = takeWhile notComma s
isNothing' : Maybe ℕ → Bool
isNothing' nothing = true
isNothing' _ = false
isNothing : List (Maybe ℕ) → Bool
isNothing l = any isNothing' l
-- wrong type, should be String -> Maybe (List N)
stringListToℕ : String → Maybe (List (Maybe ℕ))
stringListToℕ s = if (isNothing res) then nothing else just res
where res : List (Maybe ℕ)
res = map stringToℕ (map fromList(split (Data.String.toList s)))
test1 = stringListToℕ "1,2,3"
-- => just (just 1 ∷ just 2 ∷ just 3 ∷ [])
編輯
我試着寫使用from-just
轉換功能,但是這給出了一個錯誤時類型檢查:
conv : Maybe (List (Maybe ℕ)) → Maybe (List ℕ)
conv (just xs) = map from-just xs
conv _ = nothing
錯誤是:
Cannot instantiate the metavariable _143 to solution
(Data.Maybe.From-just (_145 xs) x) since it contains the variable x
which is not in scope of the metavariable or irrelevant in the
metavariable but relevant in the solution
when checking that the expression from-just has type
Maybe (_145 xs) → _143 xs
在Haskell有'序列::單子米=> [米]一個運行示例 - > M [A]'。如果Agda沒有它,你可以看看它的實現[這裏](http://hackage.haskell.org/packages/archive/base/latest/doc/html/src/Control-Monad.html#序列)。 – 2012-08-01 17:31:08
@SjoerdVisscher:Agda確實有它,它在'Data.List'中。 – Vitus 2012-08-01 17:36:01
感謝您的意見!我嘗試在列表中映射「from-just」,但這也不起作用(我以某種方式預期) – mrsteve 2012-08-01 18:24:42