我想用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