我需要一个函数,它将[Maybe a]列表作为输入,获取每个值,处理它并返回Maybe [a].如果输入列表没有Nothing,我想返回Nothing.
func [Just 1,Just 2,Just 3,Just 4,Just 5] => this returns Just [1,2,3,4,5]
func [Just 1,Nothing,Just 3,Just 4,Just 5] => this returns Nothing
Run Code Online (Sandbox Code Playgroud)
我写了这个
func mlist = if elem Nothing mlist
then Nothing
else Just $ map (\(Just e) -> e) mlist
Run Code Online (Sandbox Code Playgroud)
它有效,但我想知道我是否能做得更好.我不喜欢我所做的部分elem Nothing mlist并再次映射mlist.
为什么不能在do块中使用替换?这段代码工作正常.
test :: (x -> x) -> [x] -> [x]
test f a = map f a
main :: IO ()
main = do
let sq x = x * x :: Int
let ret = test sq [1,2,3]
print ret
Run Code Online (Sandbox Code Playgroud)
但是如果你删除do块中的let,我就会遇到编译错误.
parse error on input ‘=’
Perhaps you need a 'let' in a 'do' block?
e.g. 'let x = 5' instead of 'x = 5'
Run Code Online (Sandbox Code Playgroud)
在do块中"let x = y"等于"x < - y"吗?因此,如果右侧返回IO某事,您需要使用let(或< - )?我知道这是一个虚拟问题,但我总是遇到编译错误.EII
在下面的例子中,"try 0"工作,我得到"Nothing",而"try2 0"不起作用,我得到"Irrefutable模式失败的模式Just(x,y)"我不知道怎么得到"没什么" "from"try 0"...因为"calc n"的输出被绑定到(x,y)...请帮助我理解为什么..
try n = do
(x,y) <- calc n
return (x+1, y+1)
try2 n = (x+1,y+1)
where
Just (x,y) = calc n
calc x
| x == 0 = Nothing
| otherwise = Just (x+1, 1)
main :: IO ()
main = print $ try 0
Run Code Online (Sandbox Code Playgroud) 我写了我的 bisect_right()。它比 bisect.bisect_right() 慢 3 倍。
def my_bisect_right(a, num):
ok = len(a)
ng = -1
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if a[mid] <= num:
ng = mid
else:
ok = mid
return ok
Run Code Online (Sandbox Code Playgroud)
我创建了一个包含 10M 个整数的列表并对其运行 bisect_right()。bisect.bisect_right() 耗时 24.82 秒,而 my_bisect_right() 耗时 76.30 秒。请让我知道我在做什么错...