w12*_*220 0 recursion haskell immutability
我很难尝试编写一个函数来使用递归来查找两个列表的总和,如果任何列表为空,则可能是Nothing.
以下函数的数学运算是:
?w[i]x[i]
Run Code Online (Sandbox Code Playgroud)
其中w和x的长度等于int数组
这是我的工作代码:
example :: [Int] -> [Int] -> Int
example [] [] = 0
example (x:xs) (l:ls) = ((x*l) + (example xs ls))
Run Code Online (Sandbox Code Playgroud)
这是我想要工作的想法:
example :: [Int] -> [Int] -> Maybe Int
example [] [] = Nothing
example (x:xs) (l:ls) = Just((x*l) + (example xs ls))
Run Code Online (Sandbox Code Playgroud)
谢谢
我猜你的目的是什么,不确定我是否正确读取它:你想要Nothing在两个输入列表有不同长度时生成函数吗?
"快乐"的基础案例0就像第一次尝试一样,但被提升到了Maybe.
example [] [] = Just 0
Run Code Online (Sandbox Code Playgroud)
要处理列表具有不同长度的情况,请包括只有一个列表为空的情况.如果不包括这些情况,您应该收到有关非详尽模式匹配的编译器警告.
example [] _ = Nothing
example _ [] = Nothing
Run Code Online (Sandbox Code Playgroud)
最后一种情况是,你有两个非空列表.它看起来很像从你第一次尝试这一行,除了不直接应用除example xs ys,我们fmap在另外example xs ys,考虑的事实的优点Maybe是Functor.
example (x : xs) (y : ys) = fmap (x * y +) (example xs ys)
Run Code Online (Sandbox Code Playgroud)
用法示例:
?> example [1,2] [3,4]
Just 11
?> example [1,2] [3,4,5]
Nothing
Run Code Online (Sandbox Code Playgroud)
顺便说一下,如果你想使用一个库,safe那么将它变成一个单行的将是一个不错的选择.
import Safe.Exact
example xs ys = fmap sum (zipWithExactMay (*) xs ys)
Run Code Online (Sandbox Code Playgroud)