我有一个看起来像这样的数据库(访问它$database):
<country car_code="F" area="547030" capital="cty-france-paris">
<name>France</name>
<border country="AND" length="60"/>
<border country="E" length="623"/>
<border country="D" length="451"/>
<border country="I" length="488"/>
<border country="CH" length="573"/>
<border country="B" length="620"/>
<border country="L" length="73"/>
<border country="MC" length="4.4"/>
</country>
.....
other countries
Run Code Online (Sandbox Code Playgroud)
我想写一个函数,通过陆地边界提供从法国(或任何其他国家)可以到达的所有国家的名称.第一次尝试(可能有很多语法错误和其他错误,但程序的语义应该"更清楚"):
declare function local:reachable($country as element())
as (return value should be a sequence of countries )
{
if $country == () (:if empty, it doesn't border to any other country:)
then ()
else(
$country/name UNION (for $bord in $country/border/@country return
local:reachable ($database/country/car_code = @bord …Run Code Online (Sandbox Code Playgroud) 我已经定义了一种数据类型:
data Citizen = J11 String String | J12 String String
Run Code Online (Sandbox Code Playgroud)
我想写一个函数:getName:
getName :: Citizen -> String
getName (J11 firstName lastName ) = firstName
getName (J12 firstName lastName ) = firstName
Run Code Online (Sandbox Code Playgroud)
是否可以避免重复代码,具体取决于它是J11还是J12?没有改变类型签名?
getName (XXX firstName lastName ) = firstName
Run Code Online (Sandbox Code Playgroud)
..像这样的东西......
首先考虑以下代码,它计算字符串中的空格数:
countSpaces :: String -> Int
countSpaces [] = 0
countSpaces (c : restOfString)
= d + countSpaces restOfString
where d = if c == ’ ’ then 1
else 0
Run Code Online (Sandbox Code Playgroud)
这是我的问题:
1,如果我拨打电话:countSpaces "abc",那么当这个函数试图匹配字符串会发生什么"abc"用(c: restOfString).我的意思restOfString是:"abc"在这次通话中,但是这是(c:restOfString)什么?你正在"勉强"某事(变量?c)restOfstring 然后你想要匹配?我只是不明白.
2,我尝试运行代码但是我得到一个解析错误为什么?
输入'''上的解析错误
3,这个函数会调用countSpaces 无穷大吗?因为restOfString总是相同而不是减少,例如.countSpaces "aaa"第一次通话,第二次或任何通话后拨打电话都不会改变,对吧?
现在考虑完成相同任务的代码:
countSpaces :: String -> Int
countSpaces [] = 0
countSpaces (’ ’ : restOfString)
= 1 + …Run Code Online (Sandbox Code Playgroud)