gpt4 book ai didi

function - 如何在map函数中连接列表-Haskell?

转载 作者:行者123 更新时间:2023-12-02 14:41:43 26 4
gpt4 key购买 nike

我有两个功能:

fun1 :: Int -> [Int]
fun2 :: [Int] -> [Int]

fun2 接受 Int list 并使用 map 帮助将 fun1 应用于此列表的每个元素。但是fun1返回[Int]。所以,我有类型冲突。如何解决我的问题?

最佳答案

您可能需要结合使用 mapconcat 来实现它。假设 fun1fun2 是这样的:

fun1 :: Int -> [Int]
fun1 x = [x,x]

fun2 :: [Int] -> [Int]
fun2 = map (+ 1)

solution :: [Int] -> [Int]
solution xs = concat $ map fun1 (fun2 xs)

或者按照@CarstenKonig的建议,您可以使用concatMap

solution2 :: [Int] -> [Int]
solution2 xs = concatMap fun1 $ fun2 xs

可以进一步简化为:

solution2 :: [Int] -> [Int]
solution2 = concatMap fun1 . fun2

关于function - 如何在map函数中连接列表-Haskell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29965417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com