简体   繁体   English

Haskell-我如何走向并比较阵列/列表

[英]Haskell- how do I walk and compare down the Array/List

I am New to Haskell, but Veteran in some other languages. 我是Haskell的新手,但是其他语言的退伍军人。 (This question was taken from an Assembly language exercise, but I would like to solve it in Haskell.It is not part of homework or a test question) (这个问题来自汇编语言练习,但我想在Haskell中解决它。它不是家庭作业或测试题的一部分)

Given: An array (list) which has the values inside the list follow this pattern: 给定:列表中包含值的数组(列表)遵循以下模式:

The first item is smaller than the second item, the second item is greater than the third item, the third item is smaller than the fourth item and so on, (a "wave"). 第一项小于第二项,第二项大于第三项,第三项小于第四项,依此类推,(“波”)。

Questions: 问题:

1 How do I solve it in Haskell? 1如何在Haskell中解决它? (I know how to solve it in other languages where I can handle the array indices, but I do not know how to how solve it with a functional language. (我知道如何在其他语言中解决它,我可以处理数组索引,但我不知道如何使用函数式语言解决它。

  1. Can the answer be generalized so it can solve other patterns? 答案可以推广,以便解决其他模式吗?

This can be quite easily expressed in Haskell 这在Haskell中很容易表达

wave :: (Ord a) => [a] -> Bool
wave xs = and $ zipWith3 ($) (cycle [(<),(>)]) xs (tail xs)

We could also trivially parametrise it on the patterns 我们也可以在模式上进行简单的参数化

waveLike :: [(a -> a -> Bool)] -> [a] -> Bool
waveLike patterns xs = and $ zipWith3 ($) (cycle patterns) xs (tail xs)

twoUpTwoDown :: (Ord a) => [a] -> Bool
twoUpTwoDown = waveLike [(<),(<),(>),(>)]

coprimeThenNotCoprime :: (Integral a) => [a] -> Bool
coprimeThenNotCoprime = waveLike [coprime, notCoprime]
  where coprime m n = gcd m n == 1
        notCoprime m n = not (coprime m n)

Probie's is a very elegant solution, but perhaps a basic recursion can be more understandable for a beginner. Probie是一个非常优雅的解决方案,但对于初学者来说,或许基本的递归可能更容易理解。

wave :: (Ord a) => [a] -> Bool
wave []            = True
wave [_]           = True
wave [x1,x2]       = x1 < x2
wave (x1:x2:x3:xs) = x1 < x2 && x2 > x3 && wave (x3:xs)

The four lines of code read as follows: 四行代码如下:

A list with 0 elements is wavy. 包含0个元素的列表是波浪状的。

A list with 1 element is wavy. 包含1个元素的列表是波浪状的。

A list with 2 elements is wavy iff it is increasing. 如果它增加,则包含2个元素的列表是波浪状的。

A list with at least 3 elements starting with x1,x2,x3 is wavy iff 具有至少3个以x1,x2,x3开头的元素的列表是波浪形的iff

  1. we go "up" between x1 and x2 , 我们在x1x2之间“向上”,
  2. we go "down" between x2 and x3 , 我们在x2x3之间“向下”,
  3. the list from x3 onward (including x3 ) is wavy. x3开始(包括x3 )的列表是波浪状的。

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

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