我想把我的两个功能合二为一?

时间:2014-11-03 20:48:48

标签: haskell

我有两个功能:

firstfunc :: (RandomGen g) => g -> Int -> Float -> [[Int]]
firstfunc rnd n p = makGrid $ map (\t -> if t <= p then 1 else 0) $ take (n*n) (randoms rnd)
  where makGrid rnd = unfoldr nextRow (rnd, n)
        nextRow (_, 0) = Nothing
        nextRow (es, i) = let (rnd, rest) = splitAt n es in Just (rnd, (rest, i-1))

sndfunc firstfunc = head $ do
  lst <- firstfunc
  return $ map (\x -> if (x == 0) then 2 else x) lst

let newFunc = ((firstfunc .) .) . sndfunc

main = do
  gen <- getStdGen
  let g = (firstfunc gen 5 0.3)
  print g
  let h = sndfunc g
  print h
  print $ newFunc gen 5 0.3

firstfunc采用50.3这两个值,并返回一系列列表,例如:[[0,0,0,1,0],[1,0,0,1,0],[0,0,1,1,0],[0,0,0,0,0],[1,0,0,0,1]]

sndfunc从以上示例获取上面列表列表的头部[1,0,0,1,0],并将2替换为零,如下所示:[1,2,2,1,2]

有没有办法合并这两个函数,以便firstfunc只返回类似:[[1,2,2,1,2],[0,0,1,1,0],[0,0,0,0,0],[1,0,0,0,1]]的内容?

ERROR:

在此行上获取解析错误解析错误(可能是错误的缩进或括号不匹配):let newFunc = ((firstfunc .) .) . sndfunc

第二次编辑:

prac.hs:15:32:
    Couldn't match type ‘[b]’ with ‘a -> a1 -> b0’
    Expected type: [[b]] -> a -> a1 -> b0
      Actual type: [[b]] -> [b]
    Relevant bindings include
      newFunc :: [[b]] -> a -> a1 -> Int -> Float -> [[Int]]
        (bound at prac.hs:15:1)
    In the second argument of ‘(.)’, namely ‘sndfunc’
    In the expression: (((firstfunc .) .) . sndfunc)
Failed, modules loaded: none.

1 个答案:

答案 0 :(得分:1)

您可以使用

print $ sndfunc $ firstfunc gen 5 0.3

或者您可以定义新功能

let newFunc = ((sndfunc .) .) . firstfunc

并使用它。

print $ newFunc gen 5 0.3

(需要额外的(。)运算符,因为firstfunc需要三个输入。)