简体   繁体   English

Haskell - zip 替代品

[英]Haskell - zip alternative

I have written the following function:我编写了以下函数:

f :: String -> [(Int, Int)] 
f s = zip x y where
  x = g s 
  y = h s

The function g has the following signature:函数g具有以下签名:

g :: String -> [Int]

and h :h

h :: String -> [Int]

I want to modify f so it that it returns [(Int, Int, String)] , where String is its input s .我想修改f使其返回[(Int, Int, String)] ,其中String是其输入s I think the problem here is that zip strictly works on two lists.我认为这里的问题是 zip 严格适用于两个列表。 How can I do this?我怎样才能做到这一点?

You can make use of zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] and thus use an arbitrary function that takes elements from the two lists, and produces a value.您可以使用zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]并因此使用从两个列表中获取元素并产生值的任意函数.

In this specific case, we can for example use a lambda expression:在这种特定情况下,我们可以例如使用 lambda 表达式:

f :: String -> [(Int, Int, String)]
f s = zipWith (\xi yi -> (xi, yi, s)) (g s) (h s)

Or you can make use of the TupleSections extension [ghc-doc] , and implement this as:或者您可以使用TupleSections扩展 [ghc-doc] ,并将其实现为:

{-# LANGUAGE TupleSections #-}

f :: String -> [(Int, Int, String)]
f s = zipWith (,,s) (g s) (h s)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM