函数列表中的函数组成! [英] The composition of functions in a list of functions!

查看:128
本文介绍了函数列表中的函数组成!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义一个函数'Compose',它需要一个列表'L',它是一个函数列表。当我指定一个适合列表中所有函数的参数时,最后一个函数使用此参数评估自己。然后将结果传递给第二个最后一个函数,直到我们到达列表中的第一个项目(函数),并获得最终结果。



例如< ((fn N - > N + 1)^(fn N - > 2 * N)^#)3。


$ b

给出答案7.



我必须用我的大学讲师设计的函数式编程语言SAL(简单应用语言)因此上面有趣的语法(^ seperates list items和#marks end of list))。

如果任何解决方案都可以使用伪代码编写,使用循环,变量等,将不胜感激。显然,解决方案是一个单线的答案。我想它涉及递归(99%的任务函数做!)。

另外我不明白Haskell(猜我必须学习!)所以psuedo代码甚至纯英文都会很棒。 -



非常感谢。

一线答案,它可能涉及到一个折叠:

  compose :: [a  - > a]  - > a  - > a 
compose fs v = foldl(flip(。))id fs $ v

< a href =http://haskell.org/haskellwiki/Compose =noreferrer> http://haskell.org/haskellwiki/Compose



你也可以将它实现为一个正确的折叠,它可以按照你想要的方式工作:

  compose = foldr(。)id 

*主要>让compose = foldr(。)id
* Main>撰写[\ x - > x + 1,\ x - > 2 * x,id] 3
7


I need to define a function 'Compose' which takes a list 'L' which is a list of functions. When I specify a parameter that will suit all the functions in the list, the last function evaluates itself using this param. The result is then passed to the second last function and so on until we get to the first item (function) in the list and we get the final result.

E.g.

Compose ( ( fn N -> N + 1 ) ^ ( fn N -> 2 * N ) ^ # ) 3 .

give the answer 7.

I have to write this in a functional programming language called SAL (simple applicative language) devised by a lecturer in my college (hence funny syntax above ( ^ seperates list items and # marks end of list)).

If any solutions could be written in pseudo-code bearing in mind I can't use loops, variables etc. that would be much appreciated. Apparently the solution is a one-line answer. I imagine it involves recursion (99% of our task functions do!).

Also I don't understand Haskell (guess I'll have to learn!) so psuedo code or even plain English would be great. –

Thanks a bunch.

解决方案

If the solution is a one-line answer, it could be something involving a fold:

compose :: [a -> a] -> a -> a
compose fs v = foldl (flip (.)) id fs $ v

http://haskell.org/haskellwiki/Compose

You can also implement it as a right fold, which works the way you want:

compose = foldr (.) id

*Main> let compose = foldr (.) id
*Main> compose [\x -> x+1, \x -> 2 * x, id] 3
7

这篇关于函数列表中的函数组成!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆